-3

Whenever we define main() function in any code, why don't we pass any argument in it?

  • have a look at https://stackoverflow.com/questions/4176326/arguments-to-main-in-c. – Saboor Aug 02 '18 at 04:58
  • Show some code you have tried. Add minimal, complete, and verifiable example (https://stackoverflow.com/help/mcve) – fgamess Aug 02 '18 at 05:07

3 Answers3

8

The C++ standard sanctioned variations of main() are:

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

The C standard sanctioned variations of main() are:

int main (void) { body }
int main (int argc, char *argv[]) { body } 

There are other platform-specific variations, but all of them must return an int.

It appears that you have only seen programs that use the first version of main(). Most real-world applications use the second version of main(). It allows them to process command-line parameters.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

You only pass arguments when calling a function, but that might just be a difference in terminology between the two of us.
While defining a function we define the formal parameters, including their types.
If you have never seen a main() defined with parameters, then you have never seen a main() which can handle commandline parameters.

The usual prototype for a main() which can handle them is

int main(int argc, char **argv)

or

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

For an example of how to use this, see
https://stackoverflow.com/a/47536091/7733418

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

The main syntax is

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

In which, argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
Saboor
  • 352
  • 1
  • 10
  • 1
    "*which includes the actual name of the program*" - **usually**, but not always true in some edge cases. So `argv[0]` is the program name only when the name is actually present. – Remy Lebeau Aug 02 '18 at 05:02
  • 1
    @RemyLebeau Not always same? Can you tell us some examples? – J...S Aug 02 '18 at 05:48