2

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?

2
  • 1
    in many of implementation, char is by default signed type. Commented Apr 22, 2020 at 13:11
  • 1
    According to the C standard, void isn´t the right return type of main. It shall be an integer-compatible type or of course an int. Commented Apr 22, 2020 at 13:55

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Is integer warping the same as conversion?
"integer warping " is an example of a conversion. In this case, from an int to a signed char. 123.4 saved as an char is 123 is truncation, another form of conversion, from double to char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.