0
void main()
{
    printf("hi\n");
    return 0;
}

Why does the compiler give no error when I'm returning a value from the function main with return type void?

Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682
user3152736
  • 129
  • 1
  • 5
  • Which compiler are you using? `gcc` would emit a warning in this case, something like `'return' ..., in a function returning void`. – devnull Feb 03 '14 at 17:41
  • 2
    If you have warnings turned on, it would yield a warning. When compiled with `gcc` I get: `warning: ‘return’ with a value, in function returning void [enabled by default]` – lurker Feb 03 '14 at 17:41
  • See http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c?rq=1 – Martin Feb 03 '14 at 17:41
  • A better question is how can `main` be declared as void in the first place? Any return type other than `int` is non-standard and really just doesn't make sense for `main`. – Brandin Feb 03 '14 at 19:25

3 Answers3

1

No. It can't. You are doing wrong. You can't return anything from a function whose return type is void. Your compiler should give a warning:

[Warning] 'return' with a value, in function returning void [enabled by default] 

void main is obsolete now. The standard says about the definition of main.

5.1.2.2.1 Program startup:

1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent;10) or in some other implementation-defined manner.

haccks
  • 97,141
  • 23
  • 153
  • 244
0

Main is special.

Strictly speaking it should be

int main(int, char**);

If you deviate from that (such as by using void), the compiler will likely throw a warning (if you have warnings turned on) but produce valid code anyway.

EDIT: Apparently int main() is also valid.

zebediah49
  • 7,177
  • 1
  • 28
  • 48
  • How to turn on warnings in Visual Studio? (if you can help) Also, what if I lose on such questions in my aptitude tests or interviews because of compiler differences? whose fault is it? mine or different compilers'? – user3152736 Feb 03 '14 at 17:47
  • It would appear you don't want them *all*: http://stackoverflow.com/questions/4001736/what-with-the-thousands-of-warnings-in-standard-headers-in-msvc-wall -- but http://msdn.microsoft.com/en-us/library/vstudio/edzzzth4%28v=vs.100%29.aspx may help you – zebediah49 Feb 03 '14 at 18:02
0

Either you are, or your compiler is, doing something wrong. You can't return a value from a void function. The compiler should emit a warning, at the least.

zentrunix
  • 1,391
  • 8
  • 18