argument passing

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
#include<unistd.h>
#include<stdio.h>

int main(int argc,char *argv[]) {
int opt=0;
extern int optind,opterr,optop;
  while (opt=getopt(argc,argv,":hw:ra")!=-1) {
    switch (opt) {
      case 'h': //{
        printf("HELP IS HERE\n");
        break;
      //}
      case 'r':
      case 'a': 
        printf("OPTION: %c\n",opt);
        break;
      case 'w':
        printf("The option has an argument: %s\n","optarg");
        break;
      case ':':
        printf("%s\n","ERROR:ENTER VALUE FOR OPTION");
        break;
    }
  }
return 0;
}

Hello... is there anything wrong with the code.When i give ./(programname) -h
there is no output..
regards
Hello !!

The problem is the line 7 => while (opt=getopt(argc,argv,":hw:ra")!=-1)

The = ( atribution operator ) have a lower precedence than the != ( diferent operator ), in other words, your code on this line, is avaliable in this form => while ( opt = ( getopt(argc,argv,":hw:ra") ) != -1 ).

As you see, the getopt function are compared with the "-1" before the opt variable get the value.


To fix the problem, just put the parentheses on the right place.

while ( ( opt = getopt(argc, argv, ":hw:ra") ) != - 1 )

I make a test here, using the parentheses of this form and the program run without any problems.
ok.. die to this the problem was occouring.. thanks for helping me :-)

regards
Topic archived. No new replies allowed.