Reputation: 17303
I'm creating a presentation on how to program in C, and since I'm fairly new to C, I want to check whether my assumptions are correct, and what am I missing.
Every C program has to have an entry point for the OS to know where to begin execution. This is defined by the main()
function. This function always has a return
value, whether it be user defined or an implicit return 0;
.
Since this function is return
ing something, we must define the type of the thing it returns.
This is where my understand starts to get hazy...
int
?int main()
after the program executes?segfault
or some other error halts the program without reaching a return
statement?Upvotes: 1
Views: 166
Reputation: 476980
1 and 2 are because the language says so.
For 3: Most operating systems have some sort of process management, and a process exits by invoking a suitable operating system service to do so, which takes a status value as an argument. For example, both DOS and Linux have "exit" system calls which accept one numeric argument.
For 4: Following from the above, operating systems typically also allow processes to die in response to receiving a signal which is not ignored or handled. In a decent OS you should be able to distinguish whether a process has exited normally (and retrieve its exit status) or been killed because of a signal (and retrieve the signal number). For instance, in Linux the wait
system call provides this service.
Exit statuses and signals provide a simple mechanism for processes to communicate with one another in a generic way without the need for a custom communications infrastructure. It would be significantly more tedious and cumbersome to use an OS which didn't have such facilities or something equivalent.
Upvotes: 2
Reputation: 27854
Every program terminates with an exit code. This exit code is determined by the return
of main()
.
Programs typically return 0 for success or 1 for failure, but you can choose to use exit codes for other purposes.
Upvotes: 4