Reputation: 67
I have the following code,
void main(void) {
char x = 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1;
printf("%d", x);
}
I get the result -1
However, 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2
, already gets -128
. Can you explain why I can successfully run the code above and get the result -1
?
Also, is this an example of integer negation or overflow?
Upvotes: 2
Views: 67
Reputation: 154272
1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
is int
math with a product of 256.
1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1
is 255.
So code is like
char x = 255;
printf("%d", x);
If a char
is an unsigned char
with the range of 0...255, the output is
255
If a char
is a signed char
with the range of -128...127, the assignment converts the 255 in an implementation defined manner to a char
- likely a wrap around1 (or 255 - 256) with a value of -1. The output is
-1
char
is implemented as an unsigned char
or signed char
.
In OP's case, it is a signed char
.
A signed char
has the same range, size, encoding as signed char
, yet is a distinct type.
is this an example of integer negation or overflow?
Neither. It is an example of an implementation defined conversion. And a very common one at that.
Conversions .... Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. C17dr § 6.3.1.3 3
1 Conceptually with 2's complement encoding, the least significant byte pattern of int
255 or 0000...0000_1111_11112 is preserved as signed char
where the lead bit is a sign (or -128 place).
Upvotes: 6