You are here:

C/unsigned int and int

Advertisement


Question
Hi,

I would like to ask if it is ok to do the following:

unsigned int a;
unsigned short int b;
int c;

(a, b and c have been set to some value)

printf("%u", c)
printf("%d", a)
printf("%d", b)


when I tried out the last two printf everything seems fine but when I tried out the first printf it gave me weird number. Why is that so? Thank you.

Answer
Hello Pearson.

The first printf, printf("%u", c), may be giving you a weird display because the "%u" is causing the c to be interpreted as an unsigned integer. If you set c to a negative number, it will be interpreted, and displayed as a very large positive number.

Similarly, if you set "unsigned int a" to be a very large positive number ( > 2147483647), and use "%d" to print it, it will be displayed as a negative number.

It doesn't matter how the variables are declared. What matters is how you ask printf to interpret them. If you ask for the correct interpretation, you get the correct display.

If that doesn't answer your question, then post the actual program and be more specific about what you find to be weird.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.