C/unsigned int and int
Expert: Zlatko - 1/30/2011
QuestionHi,
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.
AnswerHello 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