开发者

So how does exit() work?

开发者 https://www.devze.com 2023-03-08 20:06 出处:网络
If I use exit(), GCC doesn\'t give a warning: int main() { exit(EXIT_SUCCESS); } If we use any other function, we will definitely meet such a warning:

If I use exit(), GCC doesn't give a warning:

int main()
{
    exit(EXIT_SUCCESS);
}

If we use any other function, we will definitely meet such a warning:

warning: control reaches end of non-void function
开发者_如何转开发

How does exit() make the parent function get its return value without using return(), which the compiler makes?


On GNU libc, exit is declared with __attribute__((__noreturn__)), which tells gcc that the function does not return.


From the docs:

The status argument is returned to the host environment.

And

Issuing a return statement from the main function is equivalent to calling the exit function with the return value as its argument.

This is implemented (in this case) via a function declaration attribute (__noreturn__) which tells the compiler that it can be treated as a return (or, more correctly, that the function will not return, so control will never reach the end of main).


instead of

 exit(EXIT_SUCCESS);

have

 return(EXIT_SUCCESS);


The problem is that you failed to include stdlib.h, and that you're not compiling with -std=c99. In C99, main implicitly returns 0 if you run off the end of it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号