Goldengirl
Goldengirl

Reputation: 967

why does the compiler give a warning for unused function?

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.

Upvotes: 1

Views: 607

Answers (2)

user281874
user281874

Reputation: 53

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

Upvotes: 0

Kninnug
Kninnug

Reputation: 8053

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.

Upvotes: 1

Related Questions