Curly braces and return value in main method

I read this code (by Bjarne Stroustrup). I got confused ... The body of the main function is not in {} , and the function does not return a value (like int ). And it works ... why?

 #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 } 
+4
source share
1 answer

This code uses the Try Block function , which is a special syntax that allows you to insert the entire piece of the function into the try / catch block (mostly useful for the class to eliminate exceptions thrown by constructors of base or member sub-objects).

In addition, main() is the only return function that does not need to explicitly return a value. If no return value is specified, 0 assumed.

In clause 3.6.1 / 5 of the C ++ 11 standard:

The return statement in main has the effect of exiting the main function (destroying any objects using automatic storage time) and calling std::exit with the return value as an argument. If control reaches the main goal without encountering a return statement, the effect is to execute

 return 0; 
+6
source

Source: https://habr.com/ru/post/1480974/


All Articles