0

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?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 2
    Because using the wrong format specifier leads to Undefined Behavior. – Spikatrix Jun 29 '15 at 10:33
  • With `scanf("%d", &a)`, you are copying `sizeof(int)` bytes into the memory address of variable `a`. But since `sizeof(a) == 1 < sizeof(int)`, this operation yields memory override, at which point your program's behavior is undefined (i.e., anything could happen). – barak manos Jun 29 '15 at 10:36

2 Answers2

4

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.

mch
  • 9,424
  • 2
  • 28
  • 42
1

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);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261