I just wanna know what happens internally when we return a value. If we dont return a value what are the consequences?
#include <stdio.h>
int main() {
printf("Hello world");
return 0; //what is use of this?
}
I just wanna know what happens internally when we return a value. If we dont return a value what are the consequences?
#include <stdio.h>
int main() {
printf("Hello world");
return 0; //what is use of this?
}
it can be evaluated by the system to determine if a program failed to run (and why it failed)
I think perhaps you have two questions:
Why does main() return int
and not void
?
This question has already been answered in many forms. Basically: for the program that called it (a shell, perhaps, or your IDE), so that it can distinguish between success and various modes of failure.
What happens if you forget to return a value from main()?
In the first standardized version of C (C89) there was nothing special about main() in this respect. If you forgot to return a value, the behavior was undefined. In practice, most compilers will act as if you had put return 0;
.
Since C99, if you do not return a value from main() explicitly, then main() is defined to return 0. main() is special in this way; other functions do not implicitly return anything.
As Weather Vane said in the comments, your program can't not return a value (on platforms where "return value" is a meaningful concept). On Linux, execve() and similar functions return an int
that is the return value of the program. If a program were ill-behaved and did not intend to return a value, the return value would probably just be some arbitrary value (but it's possible that on another platform such a program would crash).
Not every program or function returns a value. In c, we use return 0 in order to give back control to the operating system when the program is finished running and also to make sure that the program runs smoothly. Hope that helps. Cheers