【问题标题】:Curly brackets and the returned value in the main method [duplicate]大括号和main方法中的返回值[重复]
【发布时间】:2013-05-10 06:05:00
【问题描述】:

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

【问题讨论】:

    标签: c++


    【解决方案1】:

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

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

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

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

    return 0;
    

    【讨论】:

    • 只是一个问题:标准是否说明0 被假定,或者这将取决于编译器?
    • @Magtheridon96:标准规定
    • @Magtheridon96:在答案中添加了引用
    • 为什么没有出现keep_window_open("~"); 代码行?必须显示有关“〜”按的提示... std_lib_facilities.h 这里:stroustrup.com/Programming/std_lib_facilities.h >。
    • @Bush:该函数调用位于catch 处理程序中。如果在try 块内没有抛出异常,则控制权将永远不会转移到catch 处理程序,并且程序将简单地终止而不会出现异常
    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    相关资源
    最近更新 更多