0

I have heard people saying the return type of main is strictly int

 int main(){
     printf("hello world");
     return 0; // returning 0 to main indicates successful execution
 }

Instead I tried simply return.

 int main(){
     printf("hello world");
     return; // 
 }

It does not raise any warning or error. I wonder does it return 0 or some undefined value like in JavaScript?

I was reading this question return false the same as return? that says return and return false both are different in JavaScript. Is it the same in C?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
niko
  • 9,285
  • 27
  • 84
  • 131

2 Answers2

7

The C standard explicitly states as a constraint:

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

and main is no exception from that. So no this is not allowed by the standard.

What is allowed by the standard as an exception for main compared to other functions is that control may drop out of main at the end without having an explicit return statement. But these two things are not the same.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

(NOTE: This answer is incorrect. See Jens' answer.)

The C standard specifies that, in the main() function, an empty return, or falling off the end, is the same as return 0. For all other functions, it's not gonna work.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • 1
    I don't think that the term "return from the initial call to the main function" implies an explicit `return` statement without expression is allowed. – Jens Gustedt Oct 16 '13 at 11:48
  • Hm, you may be right. It's not completely clear to me whether the special-casing of `main` trumps the special casing of `return` without a value, but the latter doesn't seem to have much wiggle room. – Sneftel Oct 16 '13 at 11:52
  • 1
    After looking into the standard, I think this answer is simply wrong with respect to a `return` without expression. Please see my answer. – Jens Gustedt Oct 16 '13 at 11:56
  • @Ben, perhaps you could delete you answer? This might encourage the questioner to accept the other answer. – Aaron McDaid Oct 16 '13 at 12:05