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 Num1
error code Num3:
goto Begin; 在大括号
error code Num3

goto Begin; 在大括号(Code正确)
error code Num3


根据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"不正确,正确修改如下:
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;
}

喜欢就一键三连吧!!!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从善若水

原创不易,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值