Reputation: 171
after testing for 2-1 Exercise I found it interesting that the output from printing the value of the unsigned long integer with %d
was not correct while using %u
it was - the book did not mention %u
before yet so I think I am supposed to solve this exercise using solely %d
;
I don't want to ask for a solution as I would prefer to come to the conclusion by myself, I just wanted to ask why short unsigned int is output correctly with %d
and not the long one? It would make more sense that both wouldn't be by the definition of the type and the role of the %u in print function;
int main()
{
unsigned long int l, k;
int m = 0;
l = 1;
k = -1;
while (m < l) {
++l;
}
while (m > k) {
--k;
}
printf("%d %d", l, k); /*output is 0 -1 while if changed to %u %u output is 0 4294967295*/
return 0;
}
With short:
#include <stdio.h>
int main()
{
unsigned short int l, k;
int m = 0;
l = 1;
k = -1;
while (m < l) {
++l;
}
while (m > k) {
--k;
}
printf("%d %d", l, k); /*output is same with %d and %u 0 65535*/
return 0;
}
I tried to change the type of printed type to %u
and this worked as a solution, however it still doesn't make sense since also short is unsigned but for this also %d
gives the correct values as %u
, unlike long int, and book did not mention yet the %u
so I think it shouldn't be used;
Upvotes: 0
Views: 84
Reputation: 385488
You can find the correct conversion specifications here.
The following are relevant to this question:
Type | Conversion specification |
---|---|
signed short int |
%hd (or %d because of standard integer promotions) |
unsigned short int |
%hu (or %u because of standard integer promotions) |
signed int |
%d |
unsigned int |
%u |
signed long int |
%ld |
unsigned long int |
%lu |
Using an incorrect conversion specification results in undefined behaviour (i.e. unpredictable code).
Upvotes: 1
Reputation: 67466
The C standard (ISO/IEC 9899:2011, Section 7.21.6.1, fprintf function) states:
If a conversion specification is invalid, or if a conversion specification is not appropriate for the type of the corresponding argument, the behavior is undefined.
So your program is invoking Undefined Behaviour which means that you should not make any assumptions.
Upvotes: 1