(no subject)
Aug. 5th, 2008 11:59 am![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Dear LazyGDB..
Not knowing much about C, I find myself confused by the following, extrapolated from some code I didn't write:
Code:
Linux on PowerPC:
Linux on i686:
What is the deal?
Not knowing much about C, I find myself confused by the following, extrapolated from some code I didn't write:
Code:
#include <stdlib.h> #include <signal.h> int main(int argc, char **argv) { char opt; char *options = "a:de:f:l:p:"; opt = getopt(argc, argv, options); printf ("Opt: %d\n",opt); }
Linux on PowerPC:
suffix:~# ./test -a fish Opt: 97 suffix:~# ./test Opt: 255
Linux on i686:
vitalstatistix:~# ./test -a fish Opt: 97 vitalstatistix:~# ./test Opt: -1
What is the deal?
(no subject)
Date: 2008-08-05 04:19 am (UTC)(no subject)
Date: 2008-08-05 04:23 am (UTC)(no subject)
Date: 2008-08-05 04:27 am (UTC)It's worth noting that man 3 getopt (first point of call) tells you that -1 is returned when there are no more options to pass and that getopt() returns an 'int', not a 'char'.
(no subject)
Date: 2008-08-05 04:54 am (UTC)(no subject)
Date: 2008-08-05 11:18 am (UTC)ISO 9899 section J3.4
Date: 2008-08-05 07:57 pm (UTC)J3.4
"Which of signed char or unsigned char has the same range, representation, and behavior as ‘‘plain’’ char"
(no subject)
Date: 2008-08-05 07:59 pm (UTC)Secondly, you should be using an int anyway: getopt returns int. You didn't #include unistd.h, so you may be implicitly defining getopt, and implicitly defining it to return char.
Thirdly, PowerPC vs i686: different byteorder. This may impact the result of either of these errors.
Fourthly, -1 is the unsigned char with the same binary representation as the signed char 255.
Finally: This code depends on undefined behavior. C can do absolutely anything where the standard does not define the behavior, and due to the highly optimized nature of most C code, often does something you don't expect.