0

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!

GRY
  • 11
  • 2
  • If I understand correctly, your question is not about the result of the `^=`, but about the output of the `printf()` before it? – Hulk Jun 17 '20 at 15:16
  • 2
    `%i` expects a pointer to `int` and you are passing a pointer to `unsigned char`. That is bad. – Nate Eldredge Jun 17 '20 at 15:17

1 Answers1

2

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);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Shouldn't we also change the types of `x,y` to `signed char`, since `%i` expects a signed argument, or else use `%hhu`? – Nate Eldredge Jun 17 '20 at 15:19
  • @NateEldredge I believe there is latitude in signed vs. unsigned, but yes `%u` would be preferable. Updated. – dbush Jun 17 '20 at 15:24
  • Sure, it will work fine either way on typical platforms. I'm just being pedantic. – Nate Eldredge Jun 17 '20 at 15:26
  • Okay, got it. Thank you! I didn't think about it, because the second value was always returned correctly. Well, I should probably refresh my basics knowledge... – GRY Jun 17 '20 at 16:54