C语言 GOTO 你不知道的事情
本人就职于国际知名终端厂商,负责modem芯片研发。
在5G早期负责终端数据业务层、核心网相关的开发工作,目前牵头6G算力网络技术标准研究。
C语言 GOTO 你不知道的事情
错误Code
#include<stdio.h>
int main()
{
int a=10;
{
int b[a]; //error code Num3
Begin:
goto End;
int c[a]; //error code Num1
End: //error code Num2
int d=0;
d+=a;
int e[d]; //Correct
}
goto Begin;
return 0;
}
编译器报错内容
In function 'main':[Error] jump into scope of identifier with variably modified type
[Note] label 'End' defined here
[Note] 'c' declared here
为什么会Error
根据C11标准:
A goto statement is not allowed to jump past any declarations of objects with variably modified types. A jump within the scope, however, is permitted.
也就是说goto语句与“标签”之间的code不允许有可变长数组的声明语句。因为goto是无条件跳转语句,需要在编译时确定地址,如果可变长数组夹在其中,则编译器无法确定地址。
协议中给出一个Example:
VLA就是可变长数组
这个例子解释了上面code中的"error code Num1"和"error code Num3"为什么error,因为在"goto-identifier"的作用范围内出现了VLA,下面我们解释"goto-identifier"的作用范围,见下图:
error code Num1:
error code Num3:
goto Begin; 在大括号外
goto Begin; 在大括号内(Code正确)
根据C11标准:
A label name is the only kind of identifier that has function scope. It can be used (in a goto statement) anywhere in the function in which it appears, and is declared implicitly by its syntactic appearance (followed by a : and a statement).
也就是说"goto-identifier"中的identifier必须以 ':'和statement结尾,identifier后不能紧跟declaration,所以上面code中的"error code Num2"不正确,正确修改如下:
正确Code如下
#include<stdio.h>
int main()
{
int a=10;
int b[a]; //error code Num3
int c[a]; //error code Num1
{
int d=0;
Begin:
goto End;
End: //error code Num2
d+=a;
int e[d]; //Correct
}
goto Begin;
return 0;
}
喜欢就一键三连吧!!!
相关文章
- C语言变长数组data[0]【总结】
- C语言外部变量的使用以及erxtern的用法
- C语言/C++基础之火箭发射
- C语言/C++常见习题问答集锦(五十六) 之编程实现查找优异生的功能
- C语言/C++常见习题问答集锦(五十五) 之矩形类处理程序
- C语言面试题收集
- ZZNUOJ_C语言1078:a+b(多实例测试1)
- ZZNUOJ_C语言1014 : 求三角形的面积(完整代码)
- ZZNUOJ_用C语言编写程序实现1172:密码解密(指针专题)(附完整源码)
- ZZNUOJ_用C语言编写程序实现1292:猜素数(附完整源码)
- ZZNUOJ_用C语言编写程序实现1296:a/b + c/d(附完整源码)
- ZZNUOJ_用C语言编写程序实现1516:去师院的旅程:吃早饭先(附完整源码)
- C语言入门之自定义结构体数据struct Student { int num; char name[20]; char sex; int age; 类型
- AI模型设计:C语言实现socket发送与接受深度学习文本数据集
- C语言逆向——指针,函数指针,数组指针是比较难理解的,结构体指针要体会其编译器生成汇编代码的本质
- C语言使用技巧(二十六):通俗易懂理解C 位域
- 解决Visual Studio同一个项目工程下不同C语言程序之间互相调用的问题
- C语言运算符的优先级和结合性
- C语言入门之程序的灵魂(算法)及数据类型