return value from main

Newbie Member
1Sep2010,12:20   #1
abhishek.biradar's Avatar
check the following program
/*a.c*/
int main()
{
return 0;
}
returns 0 to the shell and echo $? gives 0
/*b.c*/
void main()
{
}
echo $? in shell gives some different values for each execution what does it represents????
Go4Expert Founder
1Sep2010,18:41   #2
shabbir's Avatar
Garbage values
Mentor
2Sep2010,11:29   #3
xpi0t0s's Avatar
It represents the fact that you haven't returned a value. The values are meaningless; you should not try to use them if the program doesn't return a value. But you should always return zero from main unless you have a good reason for returning some other specific value; zero indicates success, and for any script calling your program and relying on the return codes to check for errors a garbage return will cause undefined behaviour within the script.

If you know for certain that your program will NEVER EVER be called by a script that checks return values, and that returning garbage will definitely have no negative effects, then go ahead and return garbage. Otherwise at least return 0; it's not a difficult line to add. Or return EXIT_SUCCESS; if you prefer.
Team Leader
2Sep2010,17:01   #4
DaWei's Avatar
Always define main as returning an int, then return one. It's that simple.
Go4Expert Founder
2Sep2010,17:38   #5
shabbir's Avatar
Quote:
Originally Posted by DaWei View Post
Always define main as returning an int, then return one. It's that simple.
Offtopic comment:
After long time and so welcome back.
Go4Expert Member
7Sep2010,00:52   #6
LordN3mrod's Avatar
The current C++ standard mandates that the main() function return int. However you don't have to ACTUALLY return a value. If the control flows out of main without reaching a return statement, it is equivalent to return 0;
On the other hand,
void main() is ill-formed
shabbir like this