Why is return 0 optional?

后端 未结 4 1431
遥遥无期
遥遥无期 2020-11-27 21:48

Why, if I write

int main() 
{ 
    //... 
}

do I not need to write return 0; at the end of the main function? Do

4条回答
  •  误落风尘
    2020-11-27 22:12

    Yes. main in C is a very special function that has some extra rules. See the paragraph in the C99 standard about its termination below. In essence it says that if you quit the function without returning a value this is equivalent as if you had given a return value of 0. This is special to main, doing so with other functions where the calling function expects a return value might (and will) crash your program.

    If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

提交回复
热议问题