当前位置:网站首页>在 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,则上述程序将无法编译。
总是建议在使用之前声明一个函数,这样我们在程序运行时就不会看到任何意外。
边栏推荐
- 5、【WebGIS实战】软件操作篇——服务发布及权限管理
- Golang multi graph generation gif
- ASGNet论文和代码解读2
- shell脚本使用两个横杠接收外部参数
- Basic concept and classification of sorting
- Pyramid Scene Parsing Network【PSPNet】论文阅读
- Ridge regression and lasso regression
- IPv4 and IPv6, LAN and WAN, gateway, public IP and private IP, IP address, subnet mask, network segment, network number, host number, network address, host address, and IP segment / number - what does
- Detailed list of errors related to twincat3 ads of Beifu
- LeetCode 128最长连续序列(哈希set)
猜你喜欢

How do spark tasks of 10W workers run? (Distributed Computing)

Feign remote call and getaway gateway

Nacos

C#实现基于广度优先BFS求解无权图最短路径----完整程序展示

BluePrism注册下载并安装-RPA第一章

Bilinear upsampling and f.upsample in pytorch_ bilinear

终极套娃 2.0 | 云原生交付的封装

二叉树神级遍历:Morris遍历

Pyramid Scene Parsing Network【PSPNet】论文阅读

C#实现图的深度优先遍历--非递归代码
随机推荐
Cookie&Session
完全背包问题
The shell script uses two bars to receive external parameters
ctfshow爆破wp
shell脚本使用两个横杠接收外部参数
Valid brackets (force deduction 20)
还在浪费脑细胞自学吗,这份面试笔记绝对是C站天花板
倍福TwinCAT3 Ads相关错误详细列表
岭回归和lasso回归
[小样本分割]论文解读Prior Guided Feature Enrichment Network for Few-Shot Segmentation
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
Develop industrial Internet with the technical advantages of small programs
Subnet division and subnet summary
Feign remote call and getaway gateway
手把手带你了解一块电路板,从设计到制作(干货)
5、【WebGIS实战】软件操作篇——服务发布及权限管理
Bilinear upsampling and f.upsample in pytorch_ bilinear
md5sum操作
How to use hybrid format to output ISO files? isohybrid:command not found
后台系统右边内容如何出现滚动条和解决双滚动条的问题