27-02-2020, 02:45 PM
What exactly is meant by Rule 10.3 using "promoted type" in "The conversion of the constant expression in a switch statement’s case label to the promoted type of the controlling expression." ?
Using the promoted type kinds of contradicts the rule title, which is using essential types.
The following examples assume 10.3 uses the standard C type (after integer promotions) for the controlling expression.
Does the promotion also apply to the case labels, or do we keep using the essential type there? Assuming we keep using the essential type for case labels, that leads to some surprising violations:
Is there a way to write the following switch that is compliant on both 16-bit and 32-bit machines?
It would make more sense to use the essential type for both controlling expression and labels; or use the standard type for both.
Using the promoted type kinds of contradicts the rule title, which is using essential types.
The following examples assume 10.3 uses the standard C type (after integer promotions) for the controlling expression.
Does the promotion also apply to the case labels, or do we keep using the essential type there? Assuming we keep using the essential type for case labels, that leads to some surprising violations:
Code:
uint8_t a = 1;
switch (a) { // type promoted to "signed int"
case 1u: // 10.3 violation because 1u is essentially unsigned, but the controlling expression is promoted to an essentially signed type?
case -200: // compliant with 10.3, even though the case is impossible to reach due to the sign mismatch?
break;
}
Is there a way to write the following switch that is compliant on both 16-bit and 32-bit machines?
Code:
uint16_t num = ...;
switch (num >> 1u) { // uint16_t promotes to 'signed int' or 'unsigned int' depending on "sizeof(uint16_t) == sizeof(int)"
case 1u: // 10.3 violation where sizeof(int)>2, because the controlling expression is promoted to an essentially signed type?
case (uint16_t)2u: // 10.3 violation where sizeof(int)>2, because the controlling expression is promoted to an essentially signed type?
case 2: // I guess signed literals work in all cases, thanks to exception 3.
break;
}
It would make more sense to use the essential type for both controlling expression and labels; or use the standard type for both.
<t></t>