The following program prints "unknown" when compiled with different compilers. Why is that so?
#include "stdio.h"
const char OPTION = (char)(unsigned char)253;
int main(int argc, char* argv[])
{
unsigned char c = 253;
switch (c)
{
case OPTION:
printf("option\n");
break;
default:
printf("unknown\n");
break;
}
return 0;
}
When looking at the C++ standard (N3690 2013-05-05) I see a clause for switch:
6.4.2 The switch statement
2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.
The referenced conversion clause:
4 Standard conversions
2 [ Note: expressions with a given type will be implicitly converted to other types in several contexts:
[...]
— When used in the expression of a switch statement. The destination type is integral (6.4).
[...]
—end note ]
Variable c is of type unsigned char, which is an integral type. So no promotion should be necessary!?
If the promoted type were unsigned char
I would expect a comparison like c == (unsigned char)OPTION
which would yield true. If the promoted type were int
I would expect a comparison like (int)c == (int)OPTION)
which clearly yields false.
My questions are: What is the promoted type used in the above program? What are the relevant clauses in the C and C++ standards?