I am reading chapter 2 of Advanced Linux Programming:
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch02-writing-good-gnu-linux-software.pdf
In the section 2.1.3 Using getopt_long, there is an example program that goes a bit like this:
int main (int argc, char* argv[]) {
int next_option;
// ...
do {
next_option = getopt_long (argc, argv, short_options, long_options, NULL);
switch (next_option) {
case ‘h’: /* -h or --help */
// ...
}
// ...
The bit that caught my attention is that next_option is declared as an int. The function getopt_long() apparently returns an int representing the short command line argument which is used in the following switch statement. How come that integer can be compared to a character in the switch statement?
Is there an implicit conversion from a char (a single character?) to an int? How is the code above valid? (see full code in linked pdf)
Neither C nor C++ have a type that can store “characters” as values with some dedicated character-specific properties. In that sense, there’s no “character” type neither in C nor in C++.
In both C++ and C languages
charis an integral type. It contains numbers. It is just a smallest (in terms of range) integral type. Conversion betweencharandintexists, just like it exists betweenintandlongorintandshort.charhas no special status among other integral types (aside from the fact thatchartype it is distinct fromsigned chartype).A literal of the form
'h'in C++ has typechar, but as any other integral type it is comparable toint. That’s why you can use it incaselabel the way it is used in your original example.In other words, your original code is as “strange” as
would be. In this case the
switchargument is anint, but the case label is along. The code is valid. Do you find it surprising? Probably not. Your example with'h'is in not much different.