#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 ++中,它会导致错误。我无法理解为什么会有错误。你能告诉我怎么解决吗?
答案 0 :(得分:5)
这与静电无关。您的问题可以通过一小段代码重现,其中根本没有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。
答案 1 :(得分:3)
在C中,你被允许跳过变量的初始化,并且它将保持未初始化,给出垃圾值(或者可能是其他未定义的行为)。
在C ++中,不允许跳过变量的初始化。这是因为C ++中的变量通常是带有构造函数和析构函数的更复杂的野兽。让他们未初始化可能会使他们处于无法安全销毁的状态,使程序在需要销毁时以各种方式出错;因此,语言要求它们被正确初始化。
至少在我的编译器上,错误消息非常清楚:
test.cpp: In function ‘int main()’:
test.cpp:17:1: error: jump to label ‘b’ [-fpermissive]
test.cpp:13:6: error: from here [-fpermissive]
test.cpp:15:5: error: crosses initialisation of ‘int b’
解释跳过变量初始化是错误的。
答案 2 :(得分:0)
它不是静态的,它是C ++中的goto语句。 goto无法跨越C ++中的初始化。 http://en.wikipedia.org/wiki/Compatibility_of_C_and_C++