zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C语言 GOTO 你不知道的事情

C语言 知道 事情 goto
2023-09-14 09:13:08 时间

本人就职于国际知名终端厂商,负责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;
}

喜欢就一键三连吧!!!