user3162531
user3162531

Reputation:

Why the first code work and second give wrong output?

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

Answers (1)

haccks
haccks

Reputation: 106012

Using a wrong specifier for a data type invokes undefined behavior. Result may be expected or unexpected.

C11:7.21.6 Formatted input/output functions:

(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 following d, i, o, u, x, or X conversion specifier applies to a short int or unsigned short int argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing); or that a following n conversion specifier applies to a pointer to a short int argument.

Use h before %d and %u for short type data.

scanf("%hd %hu",&a,&l);
printf("%hd %hu",a,l);

Upvotes: 3

Related Questions