Question

How can I put the default values for main function arguments like the user defined function?

Was it helpful?

Solution

Well, the standard says nothing which prohibits main from having default arguments and say you've successfully coalesced the compiler to agree with you like this

#include <iostream>

const char *defaults[] = { "abc", "efg" };

int main(int argc = 2, const char **argv = defaults)
{
    std::cout << argc << std::endl;
}

Live example. It compiles with no errors or warnings, still it's useless; a futile experiment. It almost always would print 1.

Every time you invoke the program, say, with no arguments (or any number of arguments for that matter), argc gets set to 1 and argv[0] points to the program name, so doing it is pointless i.e. these variables are never left untouched and hence having defaults makes little sense, since the defaults would never get used.

Hence such a thing is usually achieved with local variables. Like this

int main(int argc, char **argv)
{
    int const default_argc = 2;
    char* const default_args[] = { "abc", "efg" };
    if (argc == 1)   // no arguments were passed
    {
       // do things for no arguments

       // usually those variables are set here for a generic flow onwards
       argc = default_argc;
       argv = default_args;
    }
}

OTHER TIPS

I think you want to do two different things for the following cases.

  1. When no arguments are passed
  2. When arguments are passed.

Here is how you do it.

int main(int argc, char *argv[]) 
{
    if(argc == 1)
    {
        // case #1
    }
    else
    {
        // case #2
    }
}

Using argc and argv? Thoses will pass argument from the command line to your program. You can't really use default arguments. You have to pass them during the call to your program like this :

$> ./my_addition "4" "7"



int main(int argc, char *argv[]) 
{
  // argc <=> 'argument count' (=3)
  // argv <=> 'argument vector' (i.e. argv[1] == "4")
  // argv[0] is usually the bin name, here "my_addition"

  for (int i = 0; i < argc; ++i)
    std::cout << argv[i] << std::endl;
  return (0);
}

Maybe you could use a script to run your program, this could maybe be the closest solution to default argument for main().

exec_my_prog.sh:

#!/bin/zsh
call_your_program + very_meny_args

And calling ./exec_my_prog.sh would run your program with the "default" arguments.

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