[C/CPP系列知识] 在C中使用没有声明的函数时将发生什么 What happens when a function is called before its declaration in C
2015-06-16 11:25
651 查看
http://www.geeksforgeeks.org/g-fact-95/
1 在C语言中,如果函数在声明之前被调用,那么编译器假设函数的返回值的类型为INT型,
所以下面的code将无法通过编译:
错误:其实就是fun函数定义了两遍,冲突了
将返回值改成int行可以编译并运行:
2 在C语言中,如果函数在声明之前被调用,如果对函数的参数做检测?
compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems.
编译器对参数不做任何假设,所以无法做类型检查。 下面code就会有问题,输出是garbage
输出结果:
所以It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run (See this for more details).
1 在C语言中,如果函数在声明之前被调用,那么编译器假设函数的返回值的类型为INT型,
所以下面的code将无法通过编译:
#include <stdio.h> int main(void) { // Note that fun() is not declared printf("%d\n", fun()); return 0; } char fun() { return 'G'; }
错误:其实就是fun函数定义了两遍,冲突了
test1.c:9:6: error: conflicting types for 'fun' char fun() ^ test1.c:5:20: note: previous implicit declaration of 'fun' was here printf("%d\n", fun()); ^
将返回值改成int行可以编译并运行:
#include <stdio.h> int main(void) { printf("%d\n", fun()); return 0; } int fun() { return 10; }
2 在C语言中,如果函数在声明之前被调用,如果对函数的参数做检测?
compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems.
编译器对参数不做任何假设,所以无法做类型检查。 下面code就会有问题,输出是garbage
#include <stdio.h> int main (void) { printf("%d", sum(10, 5)); return 0; } int sum (int b, int c, int a) { return (a+b+c); }
输出结果:
diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 1954607895 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 1943297623 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -16827881 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 67047927 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -354871129 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -562983177 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 33844135 diego@ubuntu:~/myProg/geeks4geeks/cpp$
所以It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run (See this for more details).
相关文章推荐
- 20150616完 一个测试注意力的小程序
- 查看Android内存的8中方法
- object-c里self与super的区别
- Android ListView滑动过程中图片显示重复错乱闪烁问题解决
- IOS 如何正确使用正则表达式
- 八款开源Android游戏引擎
- Android首选项
- Android让文本自动滚动实现
- Android开发中的ANR问题如何避免?
- Xamarin iOS教程之添加和定制视图
- Android属性动画完全解析(下),Interpolator和ViewPropertyAnimator的用法
- UI设计:APP UI设计趋势:为好设计而动
- android 比较靠谱的图片压缩
- xmpp-iOS-准备
- ios滑动返回
- android ContentObserver监听系统短信和备份短信到本地
- 一些有用的学习链接(AndroidStudio)
- Android PowerImageView实现,可以播放动画的强大ImageView
- android Handler 的使用
- android 技术总结 图片优化 sqlite使用 Fragment使用