How to set default values through a function?

hi!

I want to check if values have been set from the command line and if not set them to a default value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  /*...*/
  //->this function is meant to check if the values for host user pass and port have been 
  //from the command line and if not sets them to a default value
  static void chkVal(char *host,int port, char *user, char *pass){
  if(!host){host="SERVER"; printf("Host not set! Defaulting to SERVER\n");}
  if(!user){user="USER"; printf("user not set! Defaulting to USER\n");}
  if(!pass){pass="PASS"; printf("Password not set! Defaulting to PASS\n");}
  if(!port){port=0000; printf("Port not set! Defaulting to 0000\n");}
}

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

/*...*/
//-> the function gets the arguments from the command line
opt=getopt(argc,argv,optString);
  while(opt != -1){
    switch(opt){
      case 'h':
        host=optarg;
        break;
      case 'p':
        port=atoi(optarg);
        break;
      case 'u':
        user=optarg;
        break;
      case 'w':
        pass=optarg;
        break;
      default:
        printf("Default case reached!");
        return 1;
    }
  opt=getopt(argc,argv,optString);
  }
//->calling the function to set the variables to default
chkVal(host, port, user, pass);

/*...*/

return 0; 
}


Thanks in advance!
its much easier to just set everything to a default value up front and over-write that from your command line arg parser than to try to determine what is missing and track it all and then fill in the gaps. You are trying to hard and will end up doing too much unnecessary work and making a simple thing overly complicated.

Last edited on
Hello Rdanutalexandru,

In addition to what jonnin said remember at its least "argc" will always be 1 and the first element of "argv" will always contain the program name. From this you could check "argc" for being greater than one and less than the number of extra command line arguments that you need.

This way you could print an error message telling the user what is needed on the command line and end the program to start over or set default values for the needed variables. Although if you initialized your variables with default values when you defined them part of the problem would be eliminated from the start.

Another idea is to set a variable name in the prototype of a function with a default value. Keep in mind that in the function (prototype) default values work from right to left meaning the last variable must have a default value and enything to the left does not have to have a default value, but can.

Hope that helps,

Andy
Topic archived. No new replies allowed.