This question already has answers here:
No curly braces around main() — why does this work?

(6 个回答)


8年前关闭。




我读过这篇 code(作者 Bjarne Stroustrup)。我很困惑...... main 函数体不在 {} 中,并且函数不返回值(如 int )。它有效......为什么?
#include "std_lib_facilities.h"

int main()
try
{
    cout<< "please enter two floating-point values separated by an operator\n The operator can be + - * or / : ";
    double val1 = 0;
    double val2 = 0;
    char op = 0;
    while (cin>>val1>>op>>val2) {   // read number operation number
        string oper;
        double result;
        switch (op) {
        case '+':
            oper = "sum of ";
            result = val1+val2;
            break;
        case '-':
            oper = "difference between ";
            result = val1-val2;
            break;
        case '*':
            oper = "product of ";
            result = val1*val2;
            break;
        case '/':
            oper = "ratio of";
            if (val2==0) error("trying to divide by zero");
            result = val1/val2;
            break;
        //case '%':
        //  oper = "remainder of ";
        //  result = val1%val2;
        //  break;
        default:
                error("bad operator");
        }
        cout << oper << val1 << " and " << val2 << " is " << result << '\n';
        cout << "Try again: ";
    }
}
catch (runtime_error e) {   // this code is to produce error messages; it will be described in Chapter 5
    cout << e.what() << '\n';
    keep_window_open("~");  // For some Windows(tm) setups
}
catch (...) {   // this code is to produce error messages; it will be described in Chapter 5
    cout << "exiting\n";
    keep_window_open("~");  // For some Windows(tm) setups
}

最佳答案

该代码使用的是 Function Try Block ,这是一种特殊的语法,允许将整个函数体嵌入到 try/catch 块中(主要用于类构造函数,以捕获基类或成员子对象的构造函数抛出的异常)。

此外,main() 是唯一不需要显式返回值的返回值函数。如果未指定返回值,则假定为 0

根据 C++11 标准的第 3.6.1/5 段:

关于c++ - 大括号和main方法中的返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16568920/

10-12 17:18