So I'm using an LPC1768 using the mbed interface.
This snippet:
int16_t test = -1;
test -= 1;
printf("Value: %d\n", sizeof(test));
if (test== 0xFFFE) {
printf("It's stayed the same.\n");
} else if (test== 0xFFFFFFFE) {
printf("It's been extended.\n");
} else {
printf("None\n");
}
prints out Value: 2 It's been extended.
How could I modify this so that it will print "It's stayed the same."? The goal is to have
int16_t test = -1
make test be a 16 bit value with all bits set.
0xFFFFFFFE and 0xFFFE are both int constants. The former is out of range of int so it overflows into the negative (-2), then the short operand is widened to int (with sign extension) and the comparison succeeds. The latter is equivalent to the value 65534, which is not equal to -2.
To make the test succeed, cast the literal 0xFFFE to int16_t, which will cause it to overflow to the value -2:
if (test == static_cast<int16_t>(0xFFFE)) {
User contributions licensed under CC BY-SA 3.0