0

I just wanted to ask that-is it compulsory to use int main() in C language or can we use void main() also ? And ,is this condition is compulsory in C++ only ?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Yash Sharma
  • 811
  • 1
  • 9
  • 27

3 Answers3

8

It is best practice to use int main(void) or int main (int argc, char **argv) because C standard says it here:

C11: 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.

Other forms can also be used if implementation allows them, but better to stick with the standard form.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • "or in some other implementation-defined manner" - does it allow some other `main` definitions? – Wojtek Surowka Aug 19 '14 at 14:50
  • 1
    @WojtekSurowka: Objective-C (a super-set of C, so in theory it should be 100% C compatible) tends to use `int main (int argc, const char *argv[])`. Though not _really_ that different, the use of `const`, and it not being in the standard is a significant difference, though. in C, `argv` is definitely **not** const – Elias Van Ootegem Aug 19 '14 at 15:04
  • 1
    Unix allows ``int main( int argc, char *argv[], char *env[] )``, where env are your environment variables. Env is null terminated, allowing for use such as ``while ( *env++ )`` – Carl Aug 19 '14 at 15:23
0

There are two allowed main signatures as of c99 which all implementations must support:

int main(void);
int main(int argc, char* argv[]);

However, implementations may support any other signatures they wish, these include some adding a third argument for passed in system info or alternative return types. To find out if any exist on your system please see the compiler documentation.

Vality
  • 6,577
  • 3
  • 27
  • 48
0

Not just int main() but one can skip writing main() entirely.

main() is the entry point of a c program, this is a universal fact but actually when we dive deep, it becomes clear, that main() is called by another function called _start() which is actually the very first function called at the abstract level.

#include <stdio.h>
extern void _exit(register int);

int _start(){

printf(“Hello World\n”);

_exit(0);

}
Dmitriy
  • 5,525
  • 12
  • 25
  • 38
soda
  • 443
  • 6
  • 19