主括号中的括号和返回值

时间:2013-05-15 15:17:47

标签: c++

我读了这篇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
}

1 个答案:

答案 0 :(得分:6)

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

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

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

  

main中的return语句具有离开main函数的效果(使用自动销毁任何对象)   存储持续时间)并以返回值作为参数调用std::exit。如果控制到达终点   main没有遇到return语句,效果就是执行

return 0;