cscanfbitwise-xor

C program for xor operation, operators entered by scanf


I wrote a small program to run a bitwise XOR operation. The values shall be inserted in the command line:

#include <stdio.h>

int main()
{
    unsigned char x = 0, y= 0;

    printf("This program performs a Bitwise XOR operation of two chars\n");
    printf("Enter a value for the first variable: ");
    scanf("%i",&x);

    printf("Enter a value for the second variable: ");
    scanf("%i",&y);
    printf("1. Value = %i\n2. Value = %i\n",x,y);

    y ^= x;

    printf("Result XOR-Operation = %i", y);
    printf("\nResult in hex: 0x%x", y);

    return 0;
}

When I run the program its returns 0 for the first value...

Output of the command line:

1 This program performs a Bitwise XOR operation of two chars
2 Enter a value for the first variable: 10
3 Enter a value for the second variable: 5
4 1. Value = 0
5 2. Value = 5
6 Result XOR-Operation = 5
7 Result in hex: 0x5

I'm using gcc compiler and run it in windows command line. Do I may have to use a pointer? Couldn't find something about this topic...

Thanks in advance!


Solution

  • The %i format specifier is expecting a int *, but you're passing it a unsigned char *. Because the latter points to a smaller datatype, scanf will attempt to write past the bounds of the variable it want to write to. This causes undefined behavior.

    You want to use the hh modifier (for char) to tell scanf to expect the proper pointer type as well as the u format specifier for unsigned.

    scanf("%hhu",&x);
    ...
    scanf("%hhu",&y);