[英]Why prototype and definition of a function in C may differ?
I'm wondering why this will compile: 我想知道为什么这会编译:
int test();
int main() { return test((void*)0x1234); }
int test(void* data) { return 0; }
Why won't the compiler emit any error/warning about that (I tried clang, gcc)? 为什么编译器不会发出任何错误/警告(我试过clang,gcc)? If I change the return value it won't compile - but the arguments may differ?!
如果我更改返回值它将无法编译 - 但参数可能不同?!
If you change: 如果你改变:
int test();
to: 至:
int test(void);
you will get the expected error: 你会得到预期的错误:
foo.c:4: error: conflicting types for ‘test’
foo.c:1: error: previous declaration of ‘test’ was here
This is because int test();
这是因为
int test();
simply declares a function which takes any parameters (and is therefore compatible with your subsequent definition of test
), whereas int test(void);
简单地声明一个接受任何参数的函数(因此与你后来的
test
定义兼容),而int test(void);
is an actual function prototype which declares a function which takes no parameters (and which is not compatible with the subsequent definition). 是一个实际的函数原型,它声明了一个不带参数的函数(并且与后续定义不兼容)。
int test();
in a function declaration, no parameter means the function takes an unspecified number of arguments. 在函数声明中,没有参数意味着该函数采用未指定数量的参数。
This is different than 这不同于
int test(void);
which means the function takes no argument. 这意味着该函数不需要参数。
A function declaration with no parameter is the old C style of function declaration; 没有参数的函数声明是旧的C函数声明; C marks this style as obsolescent and discourages its use.
C将这种风格标记为过时并且不鼓励使用它。 In short, don't use it.
简而言之,不要使用它。
In your case, you should use a function declaration with the correct parameter declaration: 在您的情况下,您应该使用带有正确参数声明的函数声明:
int test(void *data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.