getopt (3) problem?

Richard M. Mathews richard at locus.com
Thu Sep 13 17:10:05 AEST 1990


bchristy at aix.aix.kingston.ibm.com (JB Christy) writes:

>In article <1990Sep12.011152.26067 at maverick.ksu.ksu.edu> proot at ksuvax1.cis.ksu.edu (Paul T. Root) writes:
>}The work around I use is like this:
>}	while(( c = getopt( argc, argv, "d:m" )), c != EOF && c != -1 ) {

This workaround makes no sense.  EOF is defined as -1 on AIX/370, AIX PS/2,
and AIX RT.  Our 6000s are being moved right now, but I strongly suspect
EOF is -1 there too (I did check a very old copy of 6000 sources and it
was defined as -1 there).

>I was bitten by something similar, and I believe the problem is that EOF is
>#define'd as -1, which is an int, and I bet you've declared c as char.  When
>the comparison occurs, c is promoted to an int but the sign is lost, so it
>becomes 255 instead of -1.  Try casting EOF to a char, e.g.

>	while(( c = getopt( argc, argv, "d:m" )) != (char) EOF ) {

>That way -1 gets "demoted" to a char and all is well.

NO!  Right idea but the answer is backwards.  It mostly works, but it's
wrong.  Look at the man page.  Getopt is defined as returning an int.
The example shows "c" being declared as an int.  The correct fix is to
declare "c" correctly, not to hack the code to make EOF have the same
incorrect type as the variable.  What would happen if the character
returned by getopt was 0xff?  A char simply can't hold each of the
possible character values and the "all done" flag, too.

Richard M. Mathews
Locus Computing Corporation
richard at locus.com
lcc!richard at seas.ucla.edu
...!{uunet|ucla-se|turnkey}!lcc!richard



More information about the Comp.unix.aix mailing list