augustine nishil
augustine nishil

Reputation: 19

different answers of scanf of a char with %d and %c

This is a program used for swapping the nibbles of a byte, which is perfect for a byte but I faced a problem.

Code:

#include<stdio.h>  

void main()
{
    unsigned char a = 0;
    scanf("%d", &a);    
    a = ((a << 4) | (a >> 4)); 
    printf("the value of a is %d\n\r", a); 
} 

You can see in the scanf statement that I've received it as %d instead of receiving it as %c which is for a char. The above code works perfectly. But if I replace %d with %c, I am getting a different undesired answer

Why?

Upvotes: 0

Views: 307

Answers (2)

mch
mch

Reputation: 9804

the correct specifier for scanfing an unsigned char is %hhu, not %d.

So scanf("%d", &a); should be scanf("%hhu", &a);.

You should also use int main(void) instead of void main() and remove the \r in the printf, because \n is a new line on every system.

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your case

 scanf("%d", &a)

is wrong. %d expects a pointer to int, not a pointer to unsigned char. it will invoke undefined behaviour.

The correct way to do it will be

 scanf("%c", &a);

or

scanf("%hhu", &a);

Upvotes: 1

Related Questions