Hello all I hope you can help me understand why getopt used an int and the handling of the optopt variable in getopt. Pretty new to C++.
Looking at getopt, optopt is defined as an integer. http://www.gnu.org/software/libtool/manual/libc/Using-Getopt.html#Using-Getopt
and the example here, http://www.gnu.org/software/libtool/manual/libc/Example-of-Getopt.html#Example-of-Getopt
In this example the part I do not understand is how `c', an integer is being compared to a char in the switch statement.
As I understand it the main argument geopt is working though is the character array argv so that fact that it deals returns an int seems strange to me, my expectation would be an char and that I would be required to cast any numerical arguments to int. Is the char being automatically converted to it's ANSI code and back again or something? The printf statment
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
Is expecting a char as I understand it, but being given an int. Why would getopt use int when it's dealing with a character array?
Am I missing something really obvious? I must be.
When an integer is compared to a character constant as in
optopt == 'c'
, the character constant actually has typeint
. In fact, in Cchar
andshort
are second-class citizens and are always promoted toint
in expressions, so it's no use passing or returning achar
; it's promoted toint
anyway.This is different from the C++ rules, but something you should be aware of when using C functions such as
getopt
andprintf
in a C++ program.The fact that
getopt
returns anint
has an additional reason: it may return either a validchar
value (typically 0..255) or -1. If you want to get achar
out ofgetopt
, you have to check for the -1 possibility first:Had
getopt
returned achar
, then there would be no way to distinguish the possibly valid(char)(-1)
(either -1 or 255) from the stop condition. See this page for a better explanation in the context of theEOF
value, which is very similar.