goto后栈的状态
State of the stack after goto
在下面的 C 代码中,f
调用 g
,g
调用 h
。注意h
中的goto
,然而:如果a
满足一定条件,它会跳回f
。
void h(int a)
{
if (a > 10)
goto out;
}
void g(int a, int b)
{
h(a);
}
void f(int a, int b)
{
g(a, b);
return;
out:
printf("b: %d\n", b);
}
我的问题是:如果 goto
被触发,堆栈将如何? g
和 h
会被取消堆叠吗? f
是否仍会打印出 b
的正确值? (或者只有在我幸运的时候它才会打印正确?)
(拜托,我不想讨论这是否是一个好习惯,或者是否应该使用它。另外,考虑到实际代码已经足够复杂,以至于编译器不会很聪明足以,例如,优化 g
out)
[我可以详细说明我为什么这样做,如果它很重要——我认为它不重要]
这个问题是无效的,因为它不能像这样完成:你只能在一个函数内 goto
,而不是函数之间。
函数之间的跳转,可以使用setjmp
/longjmp
。
C 编程中的 goto 语句提供从 'goto' 到相同函数 中的标记语句 的无条件跳转。
标签是单个函数的局部标签,您不能在不同函数之间跳转。
注意 - 在我看来,非常不鼓励使用 goto 语句。
参考:http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm
这将导致标准 C 中的未定义行为。
来自 C Language Standard 的 6.8.6.1/1:
The identifier in a goto statement shall name a label located
somewhere in the enclosing function. A goto statement shall not jump
from outside the scope of an identifier having a variably modified
type to inside the scope of that identifier.
您不能这样做,因为标签对于每个特定函数都是局部的。然而,最接近的标准等效函数是 setjmp() 和 longjmp() 对函数。那应该有效。 :)
在下面的 C 代码中,f
调用 g
,g
调用 h
。注意h
中的goto
,然而:如果a
满足一定条件,它会跳回f
。
void h(int a)
{
if (a > 10)
goto out;
}
void g(int a, int b)
{
h(a);
}
void f(int a, int b)
{
g(a, b);
return;
out:
printf("b: %d\n", b);
}
我的问题是:如果 goto
被触发,堆栈将如何? g
和 h
会被取消堆叠吗? f
是否仍会打印出 b
的正确值? (或者只有在我幸运的时候它才会打印正确?)
(拜托,我不想讨论这是否是一个好习惯,或者是否应该使用它。另外,考虑到实际代码已经足够复杂,以至于编译器不会很聪明足以,例如,优化 g
out)
[我可以详细说明我为什么这样做,如果它很重要——我认为它不重要]
这个问题是无效的,因为它不能像这样完成:你只能在一个函数内 goto
,而不是函数之间。
函数之间的跳转,可以使用setjmp
/longjmp
。
C 编程中的 goto 语句提供从 'goto' 到相同函数 中的标记语句 的无条件跳转。
标签是单个函数的局部标签,您不能在不同函数之间跳转。
注意 - 在我看来,非常不鼓励使用 goto 语句。
参考:http://www.tutorialspoint.com/cprogramming/c_goto_statement.htm
这将导致标准 C 中的未定义行为。
来自 C Language Standard 的 6.8.6.1/1:
The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.
您不能这样做,因为标签对于每个特定函数都是局部的。然而,最接近的标准等效函数是 setjmp() 和 longjmp() 对函数。那应该有效。 :)