【问题标题】:Why prototype and definition of a function in C may differ?为什么 C 中函数的原型和定义可能不同?
【发布时间】:2012-07-25 09:07:09
【问题描述】:

我想知道为什么这会编译:

int test();

int main() { return test((void*)0x1234); }
int test(void* data) { return 0; }

为什么编译器不会发出任何错误/警告(我尝试过 clang,gcc)? 如果我更改返回值,它将无法编译 - 但参数可能不同?!

【问题讨论】:

标签: c


【解决方案1】:

如果你改变:

int test();

到:

int test(void);

你会得到预期的错误:

foo.c:4: error: conflicting types for ‘test’
foo.c:1: error: previous declaration of ‘test’ was here

这是因为int test(); 只是声明了一个接受任何 参数的函数(因此与您随后对test 的定义兼容),而int test(void); 是一个实际的函数原型,它声明一个接受 no 参数的函数(并且与后续定义不兼容)。

【讨论】:

  • +1,用 C-ish 术语来说,int test() 根本不是原型,而只是一个声明。
  • 但是这种行为很快就会被弃用(或者至少这是 ISO C11 告诉我们的)。
【解决方案2】:
 int test();

在函数声明中,没有参数意味着函数接受未指定数量的参数。

这不同于

 int test(void);

这意味着该函数不带参数。

不带参数的函数声明是旧的 C 风格的函数声明; C 将这种风格标记为过时并不鼓励使用。总之,不要使用它。

在您的情况下,您应该使用带有正确参数声明的函数声明:

 int test(void *data);

【讨论】:

  • 我总是忘记 C 是这样做的!即使它是 int test(void); 但跨 TU 也不需要发出诊断。
猜你喜欢
  • 2016-04-21
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2013-01-10
相关资源
最近更新 更多