我正在编写一些 C 代码,在我的代码中有两个嵌套循环。在特定情况下,我想break
跳出内部循环并continue
外部循环。我尝试在外部循环代码的末尾使用标签来实现此目的,并且在条件下 goto
该标签。但是 gcc
给出了一个错误,我不能在复合语句的末尾添加标签。为什么不呢?
注意 1:这不是 switch
语句并且that 问题已得到回答 elsewhere .
注意 2:这不是关于样式的问题,也不是关于我是否应该使用 goto
语句或条件变量的问题。
编辑:人们要求举个例子,我可以举一个简单的例子来检查一个数组是否是另一个数组的子数组
int superArray[SUPER_SIZE] = {...}, subArray[SUB_SIZE] = {...};
int superIndex, subIndex;
for (superIndex=0; superIndex<SUPER_SIZE-SUB_SIZE; superIndex+=1)
{
for (subIndex=0; subIndex<SUB_SIZE; subIndex+=1)
if (superArray[superIndex+subIndex] != subArray[subIndex])
goto break_then_continue;
// code that executes if subArray is a sub array
break_then_continue:
}
最佳答案
在标准中明确指出标签属于语句,因此标签后的简单分号 (;
) 可以避免您遇到的问题,因为这算作语句。
6.8.3/6 中甚至有一个使用“empty”1 语句的示例。
EXAMPLE 3 A null statement may also be used to carry a label just before the closing } of a compound statement
while (loop1) {
/* ... */
while (loop2) {
/* ... */
if (want_out)
goto end_loop1;
/* ... */
}
/* ... */
end_loop1: ;
}
1 在标准中,这称为 null 语句
。
6.8.1 Labeled statements
Syntax 1 labeled-statement: identifier : statement case constant-expression : statement default : statement
请注意,statement
在上面的引用中不是可选的。
关于c - 在 C 语言中,为什么在 goto 标签后需要一个语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9730893/