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
  • 19,653
  • 7
  • 38
  • 77
Yash Sharma
  • 772
  • 1
  • 7
  • 25

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
  • 100,941
  • 24
  • 163
  • 252
  • "or in some other implementation-defined manner" - does it allow some other `main` definitions? – Wojtek Surowka Aug 19 '14 at 14:50
  • @WojtekSurowka; Updated the answer. – haccks Aug 19 '14 at 14:54
  • 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,462
  • 3
  • 27
  • 47
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,475
  • 12
  • 24
  • 37
soda
  • 413
  • 7
  • 17