#include <stdio.h>
int main()
{
goto lb;
static int a=5;
lb:
goto b;
int b=6;
b:
printf("%d %d",a,b);
return 0;
}
当我使用“.c”文件扩展名保存此代码时,它运行良好,输出为 5,后跟“垃圾”值。
但是,在 C++ 中,它会导致错误。我不明白为什么会出现错误。能告诉我怎么解决吗?
最佳答案
这与静态无关。您的问题可以用一段更小的代码来重现,其中根本没有 static
变量。
The compilation error is very clear :
main.cpp: In function 'int main()': main.cpp:12:1: error: jump to label 'b' [-fpermissive] b: ^ main.cpp:9:10: error: from here [-fpermissive] goto b; ^ main.cpp:10:9: error: crosses initialization of 'int b' int b=6; ^
C++ 有禁止 goto
跨越初始化的规则;这与它对类和对象的支持密切相关,这些类和对象通常比您可以在 C 中创建的对象复杂得多。
您应该阅读this post .
关于c++ - 无法理解 C 和 C++ 中静态的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426486/