What advanced types are used to compare switch-case expressions?

The following program prints "unknown" when compiling with different compilers. Why is this 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 suggestion for a switch:

6.4.2 switch statement

2 The condition must be an integer type, an enumeration of the type or type of the class. If the type is a class, the condition is contextually implicitly converted (section 4) to an integral or enumerated type. Integrated promotions are being implemented. Any expression in a switch statement can be marked with one or more case labels as follows:

case constant-expression :  

(5.19) . .

:

4

2 [: :
[...]
- switch. (6.4).
[...]
-end note]

c unsigned char, . !?

unsigned char, c == (unsigned char)OPTION, true. int, (int)c == (int)OPTION), false.

: , ? C ++?

+4
3

?

int, :

4.5p1 [conv.prom]

, bool, char16_t, char32_t, wchar_t, (4.13) int, prvalue int int ; prvalue prvalue unsigned int.


- ?

, char , ;

3.9.1p1 [basic.fundamental]

, char . signed unsigned.

     

...

     

char , signed char unsigned char;, .


?

, char 253.

const char OPTION = (char)(unsigned char)253;

char , , char 8 , 253 , , , OPTION -3 ,


...

if-else-statement, .

unsigned char c = 253;

//   .---------.-------------------- integral promotion
//   v         v
if ((int)c == (int)OPTION) {
  printf ("OPTION\n");
} else {
  printf ("DEFAULT\n");
}

OPTION 253, -3; , .


. ++ 11 () n3337.

+6

- " ".

, , , int, int ( int, int ).

, c, int, 253. OPTION -3, int, -3. ( a char , , - . a char , 253 -3 2s - 8- char, .)

+1

, " ". ,

switch (c)

c int 253, c .

case OPTION:

OPTION ( , char char), .

This way the control will be passed to the label defaultbecause (int) (unsigned char) 253 is not equal to (int) (signed char) 253.

0
source

Source: https://habr.com/ru/post/1543532/


All Articles