Domanda

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.

È stato utile?

Soluzione

When an integer is compared to a character constant as in optopt == 'c', the character constant actually has type int. In fact, in C char and short are second-class citizens and are always promoted to int in expressions, so it's no use passing or returning a char; it's promoted to int anyway.

This is different from the C++ rules, but something you should be aware of when using C functions such as getopt and printf in a C++ program.

The fact that getopt returns an int has an additional reason: it may return either a valid char value (typically 0..255) or -1. If you want to get a char out of getopt, you have to check for the -1 possibility first:

int i = getopt(argc, argv, option_string);
if (i == -1)
    // no more options
else {
    char c = i;
    // got a valid char, proceed
}

Had getopt returned a char, 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 the EOF value, which is very similar.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top