如果使用 goto 将控制转移到 if(false) 块会发生什么?
What happens if you transfer control to a if(false) block by using goto?
我想通过尝试解决一个困难的 'nested-condition' 问题来遵循代码:
goto error;
if (false)
{
error:
cout << "error block" << endl;
}
else
{
cout << "else block" << endl;
}
当我 运行 这段代码时,只显示 error block
,如预期的那样(我猜?)。但这种定义的行为是否适用于所有编译器?
是的,这是明确的。来自 stmt.goto#1
The goto statement unconditionally transfers control to the statement labeled by the identifier.
The identifier shall be a label located in the current function.
有一些限制,例如案例标签不能跨越非平凡的初始化
goto error;
int i = 42;
error: // error: crosses initialization of i
但是这些不适用于您的示例。此外,在交叉初始化的情况下,这是一个硬编译器错误,因此您不必担心未定义的行为。
请注意,一旦您跳转到案例标签 error
,您实际上就在 if
条件的真实分支内,通过 goto
。所以你保证 else
分支不会被执行。
我的 5 美分:
如果您的编译器有优化器,代码将按以下方式减少:
// more code here
goto error; // this go directly to the label
if (false)
{
error:
cout << "error block" << endl;
// this skips else clause
}
else
{
cout << "else block" << endl;
}
// more code here
所以编译后的代码变成了这样:
// more code here
{
cout << "error block" << endl;
}
// more code here
这里是 link 给 Godbolt 的:
https://gcc.godbolt.org/z/nY6E166Pz
(我确实稍微简化了代码以便汇编更易于阅读)
我想通过尝试解决一个困难的 'nested-condition' 问题来遵循代码:
goto error;
if (false)
{
error:
cout << "error block" << endl;
}
else
{
cout << "else block" << endl;
}
当我 运行 这段代码时,只显示 error block
,如预期的那样(我猜?)。但这种定义的行为是否适用于所有编译器?
是的,这是明确的。来自 stmt.goto#1
The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label located in the current function.
有一些限制,例如案例标签不能跨越非平凡的初始化
goto error;
int i = 42;
error: // error: crosses initialization of i
但是这些不适用于您的示例。此外,在交叉初始化的情况下,这是一个硬编译器错误,因此您不必担心未定义的行为。
请注意,一旦您跳转到案例标签 error
,您实际上就在 if
条件的真实分支内,通过 goto
。所以你保证 else
分支不会被执行。
我的 5 美分:
如果您的编译器有优化器,代码将按以下方式减少:
// more code here
goto error; // this go directly to the label
if (false)
{
error:
cout << "error block" << endl;
// this skips else clause
}
else
{
cout << "else block" << endl;
}
// more code here
所以编译后的代码变成了这样:
// more code here
{
cout << "error block" << endl;
}
// more code here
这里是 link 给 Godbolt 的:
https://gcc.godbolt.org/z/nY6E166Pz
(我确实稍微简化了代码以便汇编更易于阅读)