开发者

what does a c compiler do when doesn't find the matching function

开发者 https://www.devze.com 2023-04-09 01:00 出处:网络
Consider the following code: #include<stdio.h> int f() { printf(\" hey \"); return 5; } int main() { printf(\"hello there %d\",f(4,5));

Consider the following code:

#include<stdio.h>
int f()
{
        printf(" hey ");
        return 5;
}
int main()
{
        printf("hello there %d",f(4,5));
        f(4,5);
        return 0;
}

I expected something like too many arguments to function ‘int f()’ but it gives an output even in strict C99 compilation. why is this behavior? B开发者_JAVA技巧ut it seems like a C++ compiler gives an error.


C is much less strict than C++ in some regards.

A function signature f() in C++ means a function without arguments, and a conforming compiler must enforce this. In C, by contrast, the behaviour is unspecified and compilers are not required to diagnose if a function is called with arguments even though it was defined without parameters. In practice, modern compilers should at least warn about the invalid usage.

Furthermore, in function prototype declarations (without definition) in C, empty parentheses mean that the parameters are unspecified. It can subsequently be defined with any number of arguments.

To prevent this, use the following prototypeISO/IEC 9899 6.7.6.3/10:

int f(void)


In addition to what Konrad wrote, C will also implicitly declare functions for you. For example:

int main(int argc, char** argv)
{
  int* p = malloc(sizeof(int));
  return 0;
}

will compile (maybe with a warning) without a #include <stdlib.h> that contains the declaration.

0

精彩评论

暂无评论...
验证码 换一张
取 消