编译器将 return 确定为离开函数的信号,而不是从 swith 离开

问题描述 投票:0回答:1

我正在学习

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
类型,并且在这种情况下需要返回值。
但为什么它不将其确定为从交换机离开的信号呢?

我使用 GNU GCC 和 Windows 10。

c++ gcc g++
1个回答
0
投票

我需要使用

break
而不是
return
:

#include <iostream>


int main()
{
    switch(int x = 2)
    {
        case 2:
            std::cout << "2";
            break;
        default:
            std::cout << "other";
            break;
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.