我正在学习
c++
。我尝试用 g++ main.cpp -o main.exe
来编译它:
#include <iostream>
int main()
{
switch(int x = 2)
{
case 2:
std::cout << "2";
return;
default:
std::cout << "other";
return;
}
return 0;
}
但是,在这种情况下,编译器会产生以下错误:
main.cpp: In function 'int main()':
main.cpp:10:13: error: return-statement with no value, in function returning 'int' [-fpermissive]
10 | return;
| ^~~~~~
main.cpp:13:13: error: return-statement with no value, in function returning 'int' [-fpermissive]
13 | return;
| ^~~~~~
所以,我尝试使用
-fpermissive
选项,如错误消息中所示:g++ main.cpp -o main.exe -fpermissive
。现在,编译器产生警告,程序编译成功:
main.cpp: In function 'int main()':
main.cpp:10:13: warning: return-statement with no value, in function returning 'int' [-fpermissive]
10 | return;
| ^~~~~~
main.cpp:13:13: warning: return-statement with no value, in function returning 'int' [-fpermissive]
13 | return;
| ^~~~~~
据我了解,这种行为是因为编译器将 switch 中的
return
语句确定为离开 main
函数的信号,但它具有 int
类型,并且在这种情况下需要返回值。我需要使用
break
而不是 return
:
#include <iostream>
int main()
{
switch(int x = 2)
{
case 2:
std::cout << "2";
break;
default:
std::cout << "other";
break;
}
return 0;
}