当前位置:网站首页>在 C 中声明函数之前调用函数会发生什么?
在 C 中声明函数之前调用函数会发生什么?
2022-07-01 03:18:00 【三贝勒文子】
在 C 中,如果函数在声明之前被调用,编译器会假定函数的返回类型为 int。
例如,下面的程序编译失败。
#include <stdio.h>
int main(void)
{
// Note that fun() is not declared
printf("%c\n", fun());
return 0;
}
char fun()
{
return 'G';
}
代码编译结果:
prog.c:在函数'main'中:
prog.c:5:17:警告:函数“fun”的隐式声明 [-Wimplicit-function-declaration]
printf("%c\n", fun());
^
prog.c:在顶层:
prog.c:9:6:错误:“有趣”的类型冲突
字符乐趣()
^
prog.c:5:17:注意:先前隐含的“fun”声明在这里
printf("%c\n", fun());
如果上面代码中的函数char fun()是在 main() 和调用语句后面定义的,那么它就不会编译成功。因为编译器默认假定返回类型为“int”。并且在声明时,如果返回类型与 int 不匹配,则编译器将给出错误。
以下程序编译并运行良好,因为函数是在 main() 之前定义的。
#include <stdio.h>
int fun()
{
return 10;
}
int main(void)
{
// Note the function fun() is declared
printf("%d\n", fun());
return 0;
}
输出结果:
10
参数呢?编译器对参数没有任何假设。因此,当函数应用于某些参数时,编译器将无法执行参数类型和数量的编译时检查。这可能会导致问题。例如,以下程序在 GCC 中编译得很好,并产生了垃圾值作为输出。
#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);
}
编译器假定输入参数也是 int 存在这种误解。如果编译器假定输入参数为 int,则上述程序将无法编译。
总是建议在使用之前声明一个函数,这样我们在程序运行时就不会看到任何意外。
边栏推荐
- Listener listener
- Nacos
- Pathmeasure implements loading animation
- The combination of applet container technology and IOT
- C语言多线程编程入门学习笔记
- How do spark tasks of 10W workers run? (Distributed Computing)
- 4、【WebGIS实战】软件操作篇——数据导入及处理
- ECMAScript 6.0
- 服务器渲染技术jsp
- The shell script uses two bars to receive external parameters
猜你喜欢
How to achieve 0 error (s) and 0 warning (s) in keil5
The preorder traversal of leetcode 144 binary tree and the expansion of leetcode 114 binary tree into a linked list
4、【WebGIS实战】软件操作篇——数据导入及处理
C语言多线程编程入门学习笔记
Test function in pychram
ASGNet论文和代码解读2
TEC: Knowledge Graph Embedding with Triple Context
Hello World generation
5、【WebGIS实战】软件操作篇——服务发布及权限管理
Filter
随机推荐
Edlines: a real time line segment detector with a false detection control
C language EXECL function
FCN全卷積網絡理解及代碼實現(來自pytorch官方實現)
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
10、Scanner.next() 无法读取空格/indexOf -1
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
Subnet division (10)
Ridge regression and lasso regression
Analyze datahub, a new generation metadata platform of 4.7K star
EtherCAT简介
【伸手党福利】JSONObject转String保留空字段
How do spark tasks of 10W workers run? (Distributed Computing)
Listener listener
二叉树神级遍历:Morris遍历
5、【WebGIS实战】软件操作篇——服务发布及权限管理
[us match preparation] complete introduction to word editing formula
后台系统右边内容如何出现滚动条和解决双滚动条的问题
pytorch nn.AdaptiveAvgPool2d(1)
深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
Common interview questions for performance test