why does the compiler give a warning for unused function? - c

I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.

Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.

You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error

Related

Cannot declare a void function before the main() in C

I'm a beginner in C language and in my previous question I have asked about proper function declaration order in C. I was told that in standard C, it is necessary to declare functions before calling them.
But for the following example code I cannot declare the the function times2p before the main(). I tried to declare it as: void times2(int in_data); right before the main(), but I get errors. Here below is the example code:
#include <stdio.h>
#include <stdlib.h>
void times2p(int *in_data);
void times2(int in_data);
int main()
{
int y = 5;
int s = times2(y);
printf("%d\n", y);
printf("%d\n", s);
printf("-------------\n");
int yp = 5;
times2p(&yp);
printf("%d\n", yp);
return 0;
}
//Multiplies the input argument by two
void times2(int in_data){
in_data = in_data*2;
}
void times2p(int *in_data){
*in_data = *in_data*2;
}
How and where should the times2p function be declared in this case? If I don't declare the code still compiles without error but I was told that I have to declare the functions in C in my previous question.
Here is the error:
||=== Build: Debug in test1 (compiler: GNU GCC Compiler) ===|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c||In function 'main':|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|16|error: void value not ignored as it ought to be|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|13|warning: unused variable 'read_x' [-Wunused-variable]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
Your code in the current version of the question is incorrect, but not for the reason you're asking about.
There's nothing wrong with the void function declarations before main, and the compiler doesn't complain about them. The problem is that a void function doesn't return a value, and you're trying to call them as if they did:
int s = times2(y);
This would be correct only if times2(y) returned an int value (or a value of some type implicitly convertible to int).
Also, looking at the definition of the function:
void times2(int in_data){
in_data = in_data*2;
}
The parameter in_data is a local variable within the function. Changing its value effectively does nothing.
Your times2p function looks OK, and it should work. If you want times2() to be useful, it needs to return a value:
int times2((int in_data) {
return in_data * 2;
}
(The question has changed, so this answer may not be perfect anymore, sorry).
You need to declare at least the prototype of the functions before you use it. Like this:
#include <stdio.h>
#include <stdlib.h>
//How should the function times2p be declared here?
void times2p(int *in_data);
int main()
{
int y = 5;
times2p(&y);
printf("%d\n", y);
return 0;
}
//Multiplies the input argument by two
void times2p(int *in_data){
*in_data = *in_data*2;
}
Or declare the function itself, like this:
#include <stdio.h>
#include <stdlib.h>
//Multiplies the input argument by two
void times2p(int *in_data){
*in_data = *in_data*2;
}
int main()
{
int y = 5;
times2p(&y);
printf("%d\n", y);
return 0;
}

Warning: Variable is unitialized in this function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "scanner.h"
int WhatFell(char *typeoffood)
{
if (strcmp(typeoffood,"meat") == 0);
return 1;
}
void getData(char *typeoffood)
{
printf("What fell on the floor? ");
typeoffood = readToken(stdin);
return;
}
int main(int argc, char **argv)
{
char *typeoffood;
int x;
getData(typeoffood);
x = WhatFell(typeoffood);
printf("%s\n",typeoffood);
printf("%d\n",x);
return 0;
}
eat.c: In function ‘main’:
eat.c:14:12: warning: ‘typeoffood’ is used uninitialized in this function [-Wuninitialized]
getData(typeoffood);
^
A few notes:
'readToken' is found in the "scanner.h" inclusion and simply is a safe version of scanf() for strings.
Also please just focus on the error, this is just a snippet of code I wrote seeings if I would be able to use a function getData for string input in my program.
I'm trying to use a function to ask for user string input (which I can do fine with integers/reals) and then use the string to run another function, but I keep getting all these weird warnings though and if I run it i get a segmentation fault.
char *typeoffood;
int x;
getData(typeoffood);
typeoffood is not initialized but passed to getData() so would receive uninitialised data. NB: The numbers 12:14 in the message tell you the line numbers relevant to the error.
You should pass typeoffood as a pointer to a pointer:
getData(&typeoffood);
and give getData() the prototype:
void getData(char **);

Return array from function -conflicting types for

My purpose is to create an array in a function and then return it to the main function.
I was recommended to allocate the array on the heap in the function (otherwise popped from the stack as soon as its returned).
The code is shown below:
#include <stdlib.h>
int main() {
double *v1 = myFunction();
return 0;
}
double *myFunction() {
return malloc(10*sizeof(double));
}
When I compile this code with gcc I get the following error-message:
..\src\main3.c:38:9: error: conflicting types for 'myFunction'
What is wrong with this code? Why do I get this compilation error?
Provide myFunction()'s prototype before using it, that is before main() like so:
double * myFunction();
int main(void)
{
...
If not doing so, the compiler assumes type int for myFunction() when seeing it for the first time.
Than later it finds it to be declared as double * (being different from int) which then provokes the error.
Turning on all warnings would have pointed you to using a function without prototype. Use -Wall -Wextra -pedantic to turn on most of gcc's warnings.
Another issue is that declaring a function without any arguments specified leaves it open what to pass on calling the function:
double * myFunction();
If a function should be specfied to not have any arguments specify void as argument:
double * myFunction(void);
The same for how your code defines main(). It shall be:
int main(void);
or either be
int main(int argc, char ** argv);
1) Add prototype of myfunction at the starting like following or
double *myFunction();
int main() {
double *v1 = myFunction();
return 0;
}
double *myFunction() {
return malloc(10*sizeof(double));
}
2). or define the functionBody before it is called
double *myFunction() {
return malloc(10*sizeof(double));
}
int main() {
double *v1 = myFunction();
return 0;
}
However, first solution is preferable.
Your code is almost fine, there's only one little but blocking error, you are trying to use myFunction before the symbol is defined, all you have to do is :
#include <stdlib.h>
double *myFunction() { // myFunction should be declared before it's used
return malloc(10*sizeof(double));
}
int main() {
double *v1 = myFunction();
return 0;
}
The the open C book states "All identifiers in C need to be declared before they are used. This is true for functions as well as variables." the beauty in C is that you can do can do amazing stuff like this piece of code, but you should follow some guidelines, read the open C book!.
Cheers.
Try this..
return (double*) malloc(10*sizeof(double));

Function not returning char correctly: error during compile

I am currently trying to write a simple Rock, Paper, Scissors program in C. The entire point of the assignment is to get familiar with using chars. Here is the code I currently have. It is incomplete, as I am stuck.
#include <stdio.h>
int main()
{
int pScore = 0;
int cScore = 0;
int ties = 0;
char play, go;
char comp = 'r';
printf("Welcome to Rock-Paper-Scissors!\n");
printScore(pScore, cScore, ties);
for ( ; ;)
{
printf("Do you want to play Rock-Paper-Scissors? (y/n): ");
scanf("\n%c", &go);
if(go == 'y' || go == 'Y')
{
printf("Enter your choice (r,p,s): ");
scanf("\n%c", &play);
comp = computerPlay();
printf("Computer plays: %c", comp);
}
else
break;
}
printf("\nThanks for Playing!!\n\n");
}
char computerPlay()
{
int r = rand() % 3;
char c;
if (r == 0)
{
c = 'r';
}
else if (r == 1)
{
c = 'p';
}
else if (r == 2)
{
c = 's';
}
return c;
}
int printScore(int p, int c, int t)
{
printf("\nHuman Wins: %d Computer Wins: %d Ties: %d\n\n", p, c, t);
return 0;
}
The compiler is giving me the following error:
RPS.c:35:6: error: conflicting types for ‘computerPlay’
RPS.c:28:14: note: previous implicit declaration of ‘computerPlay’ was here
It seems to me this should be working just fine.... I'm at a loss.
you did not declare the function computerPlay()
check after declaring this function.
char computerPlay(void);
add this statement after #include<stdio.h>
EDIT:
All identifiers in C need to be declared before they are used. This is true for functions as well as variables.
For functions the declaration needs to be before the first call of the function.
A full declaration includes the return type and the number and type of the arguments
simple example :
int sum (int, int); // declared a function with the name sum
result =sum(10,20); // function call
int sum (int a, int b) // defined a function called sum
{
return a + b;
}
At the point the compiler encounters a use of a function, it needs to know about the existence of the function.
In your code, when the compiler (reading down your source file) meets comp = computerPlay();, it hasn't seen anything telling it that function exists. It has a guess at what the function is, and guesses int computerPlay(void) - by default, C will always assume a function returns int. Then it encounters the actual definition later on, which conflicts with the guess it already made - the function returns char, not int.
The solution is to make the compiler aware the function exists before you use it. You can either:
move the entire function definition above main
put a declaration static char computerPlay(void); above main, indicating it's available to this source file only
put a declaration char computerPlay(void); into a separate header file, and #include that file above main, thereby making the function available to other source files (given other steps beyond the scope of this question)
You are using two functions one is
char computerPlay() and second one is
int printScore(int p, int c, int t) both of these first must have to declared below the include statement.
So just make the following statement below the include statement.
char computerPlay();
int printScore(int , int , int );
Second thing you are also using int main() so at the end you must have to return integer so you also have to add following statement at the end of the main return 0 or any other integer.

Programming with functions using C. The functions are not executed

I'm learning C and doing the exercise of the function chapter. So i have written a small programm with 3 files and two small functions. Sincerly it does not work. I have no errors, the functions are simply not executed and i don't know why.
First of all this is my headerfile which only declares my functions.
//employee.h
int addEmployee(void);
int printEmployee(int i);
So the next file is for the definition of the functions.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int numE;
int i;
int addEmployee(void)
{
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
return i;
}
int printEmployee(int i)
{
printf("%d", i);
getchar();
getchar();
return i;
}
And the last file is used to execute the functions.
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
Using
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
you're basically declaring 2 new functions with 0 arguments.
You're not calling your "old" functions.
This should work, as others have pointed out:
int main ()
{
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Because you're calling addEmployee(), storing it's result to emp and then printing emp using printEmployee. Since printEmployee is declared with one parameter, you just put emp in and it will work.
When you call a function you do not put the return type in front of the call. The call is simply the name of the function and any parameters you are calling it with. So your main function should look like this:
int main() {
addEmployee();
printEmployee(1);
return 0;
}
EDIT: So in your employee.c file, you are trying to use addEmployee() to take a number of employees from the command line and store it in the variable i right? And you want printEmployee() to tell you how many employees were entered? Here's how you would do that.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int i;
int addEmployee(void)
{
int numE;
printf("Please type in the number of your employees: ");
scanf_s("%d", &numE);
i = numE;
}
int printEmployee()
{
printf("%d", i);
getchar();
getchar();
}
Here's what I did.
First, I made numE a variable local to the addEmployee function that uses it. Generally you should keep variable scope as small as possible. That means keep them down to the lowest level they are used. In this case, numE is only needed by addEmployee() so that's its scope.
Second, I removed the parameter from int printEmployee(int i). It was overriding your i variable at the file level. So you were storing the number read into numE in i but then when you entered printEmployee() you were creating a new, empty i that hid it. When you called printEmployee(1) from main, you were passing the value 1 into i in printEmployee(int i). By removing the parameter, you stop hiding employee.c's i.
Finally, I removed the returns. A function doesn't have to return anything in C. And if you are not going to use the return, then it's just an extra line of code to include it.
There's one more change you'll have to make to make this work, in your lab6.c file. Remove the parameter from the call to printEmployee()
//lab6.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
int main ()
{
addEmployee();
printEmployee();
return 0;
}
Should work the way you expect it now.
you want:
int main ()
{
addEmployee();
printEmployee(1);
return 0;
}
Change this:
int main ()
{
int addEmployee();
int printEmployee();
return 0;
}
To this:
int main ()
{
addEmployee();
printEmployee();
return 0;
}
You're re-declaring the functions instead of calling them.
You'll also have to change your printEmployee function to not accept an integer argument; it seems like it should just be using the same global variable as addEmployee. This is a bad idea though; global variables are generally to be avoided. addEmployee should probably return the employee ID, which you could store and then pass into printEmployee.

Resources