Reputation:
This is the first code
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int a;
unsigned short int l;
scanf("%d%u",&a,&l);
printf("%d %u",a,l);
return 0;
}
If I give the input(may be any other input)
5
9
The output is
0 9
The second code is
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int a;
unsigned short int l;
scanf("%u%d",&l,&a);
printf("%d %u",a,l);
return 0;
}
If I give the output (may be any other input)
9
5
The output is
5 9
Why scanf("%d%u",&a,&l);
do not work and scanf("%u%d",&l,&a);
works?
Upvotes: 4
Views: 163
Reputation: 106012
Using a wrong specifier for a data type invokes undefined behavior. Result may be expected or unexpected.
(p9) If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
and about h
: p(7)
h
Specifies that a followingd, i, o, u, x
, orX
conversion specifier applies to ashort int
orunsigned short int
argument (the argument will have been promoted according to the integer promotions, but its value shall be converted toshort int
orunsigned short int
before printing); or that a following n conversion specifier applies to a pointer to ashort int
argument.
Use h
before %d
and %u
for short
type data.
scanf("%hd %hu",&a,&l);
printf("%hd %hu",a,l);
Upvotes: 3