vjain27
vjain27

Reputation: 3684

printf type promotion and sign extension

I am confused about how type promotion happens in case of printf and in general. I tried the following code

unsigned char uc = 255
signed char sc = -128

printf("unsigned char value = %d \n", uc);
printf("signed char value = %d \n", sc);

This gives the following output :

unsigned char value = 255
signed char value = -128

This has left me wondering about how promotion actually takes place and whether a sign extension happens or not. If a sign extension is done then the value 255 should be printed as negative value (-128 remaining the same) and if no sign extension is done then -128 should have been printed as a positive value (255 remaining the same). Please explain.

Upvotes: 6

Views: 3031

Answers (5)

Michael Burr
Michael Burr

Reputation: 340516

If a sign extension is done then the value 255 should be printed as negative value

This is where you're wrong - all values of type unsigned char including 255, can be represented in a int, so the promotion to int from unsigned char just happens without any funny business.

Where problems occur is when a signed value must be converted (which is a different thing than promotion, and occurs to create a common type for operands) to an unsigned value. If that signed type has a negative value, then the conversion to an unsigned type will change the value.

In summary, integer promotion preserves value (including sign), conversion can change value.

Upvotes: 4

Jens Gustedt
Jens Gustedt

Reputation: 78993

A va_arg function has no information on the expected type for the ... part. Therefore the promotion rules for functions as declared without prototype apply. This means that all types that are shorter than int are promoted to int or unsigned directly. So your printf function never sees an (un)signed char.

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 60037

Both are promoted to ints - hence keeping the sign.

Upvotes: 1

MByD
MByD

Reputation: 137442

Sign extension is done.

But the since the case of uc, there is no sign, as it is an unsigned char, so it is left positive.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182883

Sign extension is done. But you can't sign extend an unsigned char because it has no sign bit. The whole point of sign extension is to keep the value the same. Or, if you prefer to think of it this way, every unsigned variable has an implied zero sign bit. So when it's sign-extended to a larger signed type, the sign bit should be zero in the larger type.

Upvotes: 2

Related Questions