If I have the following snippet:
size_t num = -1;
switch(num) {
case -1:
printf("Minus one!\n");
break;
default:
printf("Not minus one!\n");
}
Why is it that the program prints Minus One!
? Is num
casted to a size_t
in the switch
statement? Is this behavior defined?
From the C standard on switch:
6.8.4.2 The switch statement
...
Semantics
...
5 The integer promotions are performed on the controlling expression. The constant expression in each case label is converted to the promoted type of the controlling expression. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label.
size_t
is also an unsigned type per the standard (6.5.3.4 The sizeof operator, Semantics, 4).
So, your -1
is converted to size_t
in both size_t num = -1;
and case -1:
. No wonder that (size_t)-1==(size_t)-1
evaluates to true.
Yes, this behavior is defined. The values are cast to size_t
as you'd expect. From C99 §6.8.4.2/5:
The integer promotions are performed on the controlling expression. The constant expression in each
case
label is converted to the promoted type of the controlling expression. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matchedcase
label.
The "controlling expression" is the expression appearing inside the parentheses after the switch
keyword, ie num
in this case.
So, the -1
in the case label is converted to size_t
(the promoted type of num
). Since the value of num
is just that, the code in that case statement is executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.