What is purpose of return type in main function in C?

What is the purpose of “return 0” in main () function in C and why not to prefer using void like “void main()”?

Here’s the main function declaration example with return 0,

int main(){
	
	printf("Hello");

	return 0;
}

Question: What is purpose of return type in main() function in C? For example, we have written “int main ()”, means, it returns integer value. So, we are using “return 0”. What is purpose of return 0?

We could have written “void main()” and does not return 0. In this case program also runs fine. So, why not void main()? 

So, the complete question is,

Why to write “int main(), not “void main()” and what is purpose of “return 0”?

ANSWER:

We use “int main()” because the C standard requires it. In other words, the main function signature requires it.

Technically, you can use void main, but it’s bad practice. Note that for simple programs it doesn’t matter. For complicated ones, or ones running on embedded devices, it absolutely matters that main returns an int.

Note that C Programs always starts processing from main function and the return type is the type of value that a function return.

Purpose of “return 0”?

We use “return 0”, because the return value indicates whether the program ended successfully or not. It is also used to indicate, why the program is crashed (after a program terminates, the return code is stored by the OS).

Success => return 0; any other value indicates an error. However, error code can be different for windows and Linux. While it is often not used by some, it is good practice to use it. (If you have void main() -> the return code is always 0 = success.

NOTES:

FYI, what is purpose of “return 0” in main () function is a frequently asked interview question in C. I have observed this question asked to even 10+ years of experience professional and freshers as well.

At least keep in mind that, in

int main(){
	
	printf("Hello");

	return 0;
}
  • “int main()” because the C standard requires it.
  • “return 0”, indicates whether the program ended successfully or not.
  • if you write “return -1” or “return 1” etc. program is returning error, even though the program does not have any error. Better to write “return 0” as successful code.

Related Posts