0

I don't understand the following piece of code:

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

// See if we've been given a seed to use (for testing purposes).  When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.

  unsigned int seed = 0;
  for(int ii=1; ii<argc; ii++) {
    if(strcmp(argv[ii++],"seed") == 0) {
      seed = atoi(argv[ii]);
    }
  }

How can I pass a value to main function? I read a bit and found out that it is called parsing, could you please clarify what is it?

Thanks,

Peet
  • 55
  • 1
  • 5

1 Answers1

1

The parameters int argc and char** argv are automatically passed to main and are parsed from the command line used to invoke the program. They are, respective, the number of command line parameters including the program name itself and an array of pointers to C-style strings of these parameters. So if the following is used to invoke my_prog:

./my_prog file 10

main gets called with argc set to 3 and argv is a char* array of 3 pointers to "./my_prog", "file" and "10"

EDIT: thanks to @BasileStarynkevitch for pointing out on POSIX complaint systems argv will have an argc + 1 element of NULL to also indicate end of parameters.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • Thank you, just to clarify what I understood from you, the loop is for checking if an input "seed" was given and the value corresponding to it, right? – Peet Jan 01 '17 at 16:49
  • Going by the code posted, the code is looking for something like `./my_prog seed 10` (check out the docs for the ++ prefix and postfix operators, they're a bit tricky to understand). Oh, and BTW -- if this is just test code, that's fine, otherwise this is kinda bad code for various reasons. – uliwitness Jan 01 '17 at 17:11
  • @uliwitness thanks, my bad. Peer - yes the loop is finding `"seed"` and setting the `seed` variable to the integer value of the next parameter string. – Paul Evans Jan 01 '17 at 17:14
  • Actually, (in your example) `argv` has even a fourth element, which is certain to be `NULL` (at least on POSIX systems) – Basile Starynkevitch Jan 01 '17 at 17:37
  • @BasileStarynkevitch good point. Edited answer accordingly – Paul Evans Jan 01 '17 at 18:22