Wrong result when comparing xor and int
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
gcc-4.8 (Ubuntu) |
Invalid
|
Undecided
|
Unassigned |
Bug Description
Hello,
I'm on Ubuntu 14.04 LTS (64bits)
With gcc:
gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
lsb_release -rd
Description: Ubuntu 14.04.3 LTS
Release: 14.04
apt-cache policy gcc
gcc:
Installé : 4:4.8.2-1ubuntu6
Candidat : 4:4.8.2-1ubuntu6
Table de version :
*** 4:4.8.2-1ubuntu6 0
500 http://
100 /var/lib/
So:
3 ^ 1 = 2 ok?
Try this code:
#include <stdio.h>
int main()
{
printf("%d\n", 3 ^ 1);
if(3 ^ 1 == 1)//Bug in this test
{
printf("SURPRISE !\n");
}
else
{
printf("FAIL !\n");
}
return 0;
}
Just compile this with defaut options:
gcc -o youprogram yourfile.c
Then, run, and you will see:
2
SURPRISE !
So, normally it will show "FAIL !", because 3 ^ 1 = 2, and 3 ^ 1 == 1 must return 0, but this test return 1 !
If you do this:
int v = 3 ^ 1;
if(v == 1)//This test work normally
{
}
And:
if((int) (3 ^ 1) == 1)//This test work normally
{
}
Globally, if you have:
int x, y, z;//Choose random values for this
if(x ^ y == z)//Return always true
{
}
The invert is bugged too:
if(z == y ^ x)//Same thing
{
}
I don't know if this bug is fixed on more recent releases, but a patch is welcome for this version :)
Thank you :)
This is a standard gotcha in C operator precedence: == has higher precedence than ^, and so your expression is parsed as 3 ^ (1 == 1), which is indeed non-zero. To fix it, use explicit parentheses as follows: (3 ^ 1) == 1.
It would perhaps be nice if the C language had been defined differently (Wikipedia mentions this, for instance: https:/ /en.wikipedia. org/wiki/ Operators_ in_C_and_ C%2B%2B# Criticism_ of_bitwise_ and_equality_ operators_ precedence), but we're stuck with it now, and GCC certainly cannot arbitrarily decide to change the language's operator precedence.