What are the differences between: main(){}, int main(){} and int main(void){} [duplicate]

StackOverflow https://stackoverflow.com/questions/19583480

  •  01-07-2022
  •  | 
  •  

Question

I am currently learning C and I have written many small programs. However, I have noticed that the main function could start as

    main()
    {
       //code
    }

or

    int main()
    {
      //code
      return 0;
    }

or

    int main(void)
    {
       //code
       return 0;
    }

Which option should I use? Thanks!

Was it helpful?

Solution 2

Your first example uses a feature inherited from the outdated dialect of C which predated the first ANSI(1989) and ISO(1990) standard: namely, that you can write a function which doesn't specify its return type, and in that case the type defaults to int.

In early C, the void keyword and associated type did not exist. When programmers wanted to write procedures ("functions that have a side effect, but do not return anything"), they simulated it using this feature. They wrote a function without any keyword specifying the return type. They allowed the function to execute to it last statement without returning a value (or alternatively, they used return; to exit from the middle without supplying a value), and they wrote the calls to the function such that those calls did not try to use the return value:

parse_input() /* similar to a procedure in Pascal, but fake! */
{
   /* ... */
   if (condition())
     return; /* no value */
   /* ... */
   /* fall off end here */
}

int main()
{
   parse_input(); /* no return value extracted, everything cool! */
   return 0;
}

Unfortunately, some programmers also started not caring about the termination status of a program and writing main itself in this procedure style:

main()
{
  /* do something */
  /* fall off the end without returning a value */
}

(A mixed style also existed: omitting the int declarator but returning an integer value.)

These programs failing to return a value had an indeterminate termination status. To the operating system, their execution could look successful or failed. Woe to the script writer who tried to depend on the termination status of such a program!

Then things took a turn for the worse. C++ came along and introduced void, and it was adopted into C. With the void keyword in C++, one could declare a function that actually returns nothing (and make it an error to have a return; statement in any other kind of function). The dummy programmers who used to write main with no return type got dumber, and started sticking this new-fangled, fresh-out-of-C++ void in front:

void main() /* yikes! */
{
  /* do something */
  /* fall off the end without returning a value */
}

By this time they had forgotten that when they wrote main(), it actually meant int main(), which made the function have a compatible type with the startup call invoked by the environment (except for the matter of neglecting to return a value). Now they actually had a different function type from the expected one, which might not even be successfully called!

Where things stand now is that in C++ and in the latest C++ standard, main is still required to return an int. But both languages make a concession for the original dummy programmers: you can let execution "fall off" the end of main and the behavior is as if return 0; had been executed there. So this trivial program now has a successful termination status as of C99 and, I think, C++98 (or possibly earlier):

int main()
{
}

But neither language makes a concession for the second-generation dumber programmers (and everyone else who read the C books that those programmers wrote in the 1980's and since). That is, void is not a valid return declarator for main (except where it is documented by platforms as being accepted, and that applies to those platforms only, not to the portable language).

Oh, and allowance for the missing declarator was removed from C in C99, so main() { } is no longer correct in new dialects of C, and isn't valid C++. Incidentally, C++ does have such a syntax elsewhere: namely, class constructors and destructors are required not to have a return type specifier.

Okay, now about () versus (void). Recall that C++ introduced void. Furthermore, though C++ introduced void, it did not introduce the (void) argument syntax. C++ being more rigidly typed introduced prototype declarations, and banished the concept of an unprototyped function. C++ changed the meaning of the () C syntax to give it the power to declare. In C++, int func(); declares a function with no arguments, whereas in C, int func(); doesn't do such a thing: it declares a function about which we do not know the argument information. When C adopted void, the committee had an ugly idea: why don't we use the syntax (void) to declare a function with no arguments and then the () syntax can stay backward compatible with the loosey-goosey legacy behavior pandering to typeless programming.

You can guess what happened next: the C++ people looked at this (void) hack, threw up their arms and copied it into C++ for the sake of cross-language compatibility. Which in hindsight is amazing when you look at how the languages have diverged today and basically no longer care about compatibility to that extent. So (void) unambiguosly means "declare as having no arguments", in both C and C++. But using it in C++ code that is obviously pure C++ never intended to be C is ugly, and poor style: for instance, on class member functions! It doesn't make much sense to write things like class Foo { public: Foo(void); virtual ~Foo(void) /*...*/ };

Of course, when you define a function like int main() { ... }, the function which is defined has no arguments, regardless of which language it is in. The difference is in what declaration info is introduced into the scope. In C we can have the absurd situation that a function can be fully defined, and yet not declared, in the same unit of program text!

When we write main, usually it is not called from within the program, and so it doesn't matter what the definition declares. (In C++, main must not be called from the program; in C it can be). So it is immaterial whether you write int main() or int main(void), regardless of whether you're using C or C++. The thing which calls main does not see any declaration of it (that you write in your program, anyway).

So just keep in mind that if you write:

int main()  /* rather than main(void) */
{ 
}

then although it is perfect C++ and correct C, as C it has a slight stylistic blemish: you're writing an old-style pre-ANSI-C function that doesn't serve as a prototype. Though it doesn't functionally matter in the case of main, you may get a warning if you use some compilers in a certain way. For instance, GCC, with the -Wstrict-prototypes option:

test.c:1:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]

Because -Wstrict-prototypes is a darn useful warning to turn on when programming in C, for improved type safety, (along with -Wmissing-prototypes), and we strive to eliminate warnings from our compile jobs, it behooves us to write:

int main(void) /* modern C definition which prototypes the function */
{
}

which will make that diagnostic go away.

If you want main to accept arguments, then it is int main(int argc, char **argv) where the parameter names are up to you.

In C++, you can omit parameter names, so this definition is possible, which serves nicely in the place of main().

int main(int, char **) // both arguments ignored: C++ only
{
}

Since the argument vector is null-pointer-terminated, you don't need argc, and C++ lets us express that without introducing an unused variable:

#include <cstdio>

int main(int, char **argv)  // omitted param name: C++ only
{
  // dump the arguments
  while (*argv)
    std::puts(*argv++);
}

OTHER TIPS

For Standard C

For a hosted environment (that's the normal one), the C99 standard says:

5.1.2.2.1 Program startup

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;9) or in some other implementation-defined manner.

9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and so on.

This (is valid in C89) main() implicitly meant (previously) int main(void). However the default return type rule has been abandoned in C99. Also:

main() means - a function main taking an unspecified number of arguments of.

main(void) means "a function main taking no arguments.

first :

declares a function main - with no input parameters. Although main should have returns ( your compiler will take care of this )

2nd/3rd:

Declare a function main which returns an int and takes in no input parameters

You should use 3rd format. Rather this is the best way:

int main(int argc, char *argv[]){
     return 0;
}

You should use 1 one of these 4 choices:

int main(void);
int main();

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

where it's conventional to use the names argc and argv; you can change them but don't.

Take care never to use void main(void); which is too-often seen in production code.

  1. By default main function returns an integer type, hence its "int main()" or you can give simply "main()"

  2. "main(void)" is same as "main()", it tells the compiler that main function has no arguments.

  3. In case if you want to pass arguments via main function:

    int main(int argc, char *argv[]){ return 0; }

main(){} 

The above line give you an error. The default return type of any function in c is int. As the above code return nothing it gives you an error.

int main(){
//body
return 0;
}

In above code it fulfill all requirement so the above code will run.In above code we pass no argument in the function. So this function can take global and local variables to process.

int main(void)
{
   //code
   return 0;
}

In above code we pass no argument in the function. But specifying void tells the compiler that it does not take any argument. void is the default datatype of argument that signifies no input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top