C++中使用goto语句可以跳到指定的函数末端,在使用g++编译时,要注意在goto语句出现之后是不允许出现新申明的变量,所以需要申明变量需要放在所有goto语句之前。(VisutalStudio编译无此问题)。
#include <iostream>
void Test(int m)
{
int i = m;
if (i > 10) goto res;
int j = i;
res:
std::cout<<"m > 10"<<std::endl;
}
int _tmain()
{
Test(4);
return 0;
}
此时使用g++编译报错:
root@ubuntu:/home/Temp# g++ -c temp.cpp
temp.cpp: In function ‘void Test(int)’:
temp.cpp:12:1: error: jump to label ‘res’ [-fpermissive]
res:
^
temp.cpp:7:19: error: from here [-fpermissive]
if (i > 10) goto res;
^
temp.cpp:10:6: error: crosses initialization of ‘int j’
int j = i;
将Test方法中代码做如下修改即可:
{
int i = m;
int j;
j = i;
res:
std::cout<<"m > 10"<<std::endl;
}