C功能与无型指标仍然有效参数? [英] C Function with parameter without type indicator still works?

查看:121
本文介绍了C功能与无型指标仍然有效参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是如下:

int func(param111)
{
    printf("%d\n", param111);
    return param111;
}

int main()
{
    int bla0 = func(99);
    int bla1 = func(10,99);
    int bla2 = func(11111110,99,10001);
    printf("%d, %d, %d\n", bla0, bla1, bla2);
}

编译结果是:

zbie@ubuntu:~$ gcc -Wall -g -std=c99 -O2 zeroparam.c

zeroparam.c: In function ‘func’:

zeroparam.c:2: warning: type of ‘param111’ defaults to ‘int’

运行结果是:

zbie@ubuntu:~$ ./a.out

99

10

11111110

99, 10, 11111110

我知道code应该是确定的,如果零参数,如int FUNC(),它接受的任何输入FUNC。但这是如何code被编译并运行成功?

I know the code should be ok if the func with zero parameters, such as int func() which will accept any inputs. But how does this code get compiled and ran successfully?

推荐答案

此行​​为是提供与旧版本语言,K&放大器的向后兼容性;该语言中的R版本。 GCC时遇到一个旧式的功能,它符合老K&安培; R C的行为,这意味着在这种情况下没有警告

This behaviour is to provide backwards compatibility with older versions of the language, the K&R version of the language. When GCC encounters an "old style" function, it conforms to the old K&R C behaviour which implies no warnings in this situation.

事实上,如果你改变的功能: INT FUNC(INT param111),您获得预期的警告:

Indeed, if you change the function to: int func(int param111), you do get the expected warnings:

x.c: In function ‘main’:
x.c:11:5: error: too many arguments to function ‘func’
x.c:2:5: note: declared here
x.c:12:5: error: too many arguments to function ‘func’
x.c:2:5: note: declared here
x.c:14:1: warning: control reaches end of non-void function [-Wreturn-type]

(使用GCC 4.7.3测试和GCC -std = C99 -Wall x.c&放大器;&安培; ./a.out)

还是要报价 JeremyP 从注释:在K&放大器; RC这是完全正常的调用函数,只要你喜欢,因为省略号当时并没有发明了许多争论。

请注意,一个编译器可以显示它想尽可能多的额外的警告,并仍然符合标准。例如苹果的编译器警告这个code。

Note that a compiler can show as many extra warnings it wants and still conform to the standard. For instance Apple's compiler warns about this code.

这篇关于C功能与无型指标仍然有效参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆