c void main function? returning 16 value
I am writing a c program with void main function in code blocks.
I just write return with no value.
The program is as below:
#include<stdio.h>
void main (void)
{
printf ("ali tariq\n");
return;
}
However, in the console window the program returns the value 16 in the console window. "Process returned 16"
I want to know why it is returning this value?
How can i utilize this value in windows using codeblocks?
Thanks
In (hosted) C the main
function must return an int
(C11§5.1.2.2.1[1]). By declaring it with a return type of void
, and not specifying any return value you invoke undefined behaviour. This means the compiler is free to return anything and in your case it turns out to be 16.
You are not free to declare the return type of main
as you wish. Why?
- BECAUSE YOU DIDN'T WRITE THE CODE CALLING main(). Sorry 'bout the shouting, but someone else wrote that code and placed it in
crt0.o
or so. Your main() is linked against that code and it can't just return what it wants because that code expects anint
. Always. It's already written and compiled. You understand this subtle point? - Because the C Standard says so. See other answer by Kninnug for Chapter and Verse.
In other words, your code invokes undefined behavior and it should be no surprise to find a garbage value where no value was provided.
So you expected a warning from the compiler? The better ones indeed will catch this with the right options. E.g. gcc and clang support -Wmain-return-type
.