c++ - Understanding getopt() example. Comparison of int to char -
hello hope can me understand why getopt used int , handling of optopt variable in getopt. pretty new c++.
looking @ getopt, optopt defined integer. http://www.gnu.org/software/libtool/manual/libc/using-getopt.html#using-getopt
and example here, http://www.gnu.org/software/libtool/manual/libc/example-of-getopt.html#example-of-getopt
in example part not understand how `c', integer being compared char in switch statement.
as understand main argument geopt working though character array argv fact deals returns int seems strange me, expectation char , required cast numerical arguments int. char being automatically converted it's ansi code , again or something? printf statment
fprintf (stderr, "unknown option `-%c'.\n", optopt); is expecting char understand it, being given int. why getopt use int when it's dealing character array?
am missing obvious? must be.
when integer compared character constant in optopt == 'c', character constant has type int. in fact, in c char , short second-class citizens , promoted int in expressions, it's no use passing or returning char; it's promoted int anyway.
this different c++ rules, should aware of when using c functions such getopt , printf in c++ program.
the fact getopt returns int has additional reason: may return either valid char value (typically 0..255) or -1. if want char out of getopt, have check -1 possibility first:
int = getopt(argc, argv, option_string); if (i == -1)     // no more options else {     char c = i;     // got valid char, proceed } had getopt returned char, there no way distinguish possibly valid (char)(-1) (either -1 or 255) stop condition. see this page better explanation in context of eof value, similar.
Comments
Post a Comment