-4

Why does this code:

strcmp(myfunction(0), "OK");

where myfunction is defined like this:

char *myfunction(int p)
{
    if (p == 0)
    {
        return("OK");
    }
}

give the following error:

warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast
ian93
  • 1,488
  • 4
  • 24
  • 37

3 Answers3

3

Because the compiler doesn't know the definition for myfunction() at the time it is called. Then the compiler presumes it returns an int ... and gives that message.

Solution: provide a prototype for the function (or its definition, which serves as a prototype) before calling it.

pmg
  • 106,608
  • 13
  • 126
  • 198
2

Do you have a prototype above the call? The function should be either prototyped or be defined before it is used. Otherwise the compiler will assume that it has a default return type of int.

// Prototype
char *myfunction(int p);

int main()
{
    // Use
    strcmp(myfunction(0), "OK");
}

// Definition
char *myfunction(int p)
{
    ...
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Great, that works! I thought it was a pointer problem... so I started applying * and & at random. Should've come here first! – ian93 May 09 '13 at 18:39
2

To build on John's answer, most C compilers will allow you to call a function that is not yet known by the compiler. This allows you to separate the implementation of your functions from the call site in the hope that it will allow incremental building, and allow you to use functions from external sources.

In this case the compiler assumes the function returns an int, and all arguments are of typeint as the compiler hasn't been provided a function prototype (either outside any function in the file or in a header file). The reasons for the compiler making this assumption are historical and are based on the development of K&R C

If you turn on strict ansi mode (-std=c99 -pedantic for gcc) the file will fail to compile because it is generally accepted as a bad idea to call a function without knowing the argument types.

This is why you get the warning.

You should put the following at the top of your source file:

char *myfunction(int p);

note the semicolon at the end of the line tells the compiler this is a function prototype and not the implementation - which the compiler assumes comes from some other translation unit.

  • 1
    Good explanation, but I have one small point of disagreement. While implicit int is indeed no longer part of the standard, it seems you're implying that unspecified argument lists aren't either. If so, this is (unfortunately) not the case. It's been deprecated but not disallowed. See section 6.11.6 of the C11 spec and http://ideone.com/eTOS5V for an example. If I misinterpreted you, I apologize. – jerry May 10 '13 at 01:46
  • @jerry Yep, that example compiles in strict ANSI mode without warning. What have the standards bodies been doing? –  May 10 '13 at 10:54