Standard word C in switch statement

Consider this code example:

char c = 0xff; char mask = 0xfe; switch ((unsigned)(c & mask)) { case -2: /* do task 1 */ break; default: /* do task 2 */ } 

Suppose CHAR_BIT = 8, and the implementation assigned to c and the mask is the interpretation of bit patterns: 11111111 and 11111110, and negative zeros are allowed. Therefore, the behavior of this code:

if char is signed and the implementation uses 2 additions, c = -1, mask = -2, c & mask = -2, (unsigned)(c & mask) = UINT_MAX - 1 .

if char is signed and the implementation uses 1 complement, c = 0, mask = -1, c & mask = 0, (unsigned)(c & mask) = 0 . c is zero, not negative zero, because C does not allow you to create a negative zero through assignment.

if char is signed and the implementation uses a signed value, c = -127, mask = -126, c & mask = -126, (unsigned)(c & mask) = UINT_MAX - 125

if unsigned char c = 255, mask = 254, c & mask = 254, (unsigned)(c & mask) = 254

The case -2 constant is converted to the same type as the control expression, so the value of UINT_MAX - 1 . Therefore, this will only match if the char is signed, and the implementation uses 2 additions.

Is this correct according to the C standard, or are there additional assumptions that need to be added?

+4
source share
1 answer

Is this correct according to standard C

Not really. If char signed and 8-bit (i.e. CHAR_MAX less than 255), then the string

 char c = 0xff; 

determined by implementation. He may do what you say, but it may not be so.

Standard C 6.3.1.3:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is determined by the implementation or a signal determined by the implementation is generated.

+1
source

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


All Articles