Ferenc Deak
Ferenc Deak

Reputation: 35448

C++ Strange behaviour for comparison with XOR value

Let's take the following program (called charco.cpp and intentionally starts with //):

//
#include <iostream>
#include <stdio.h>
int main()
{
    FILE* fp = fopen("charco.cpp", "rt");
    char c = fgetc(fp);
    if(c == '/')
    {
        char c2 = fgetc(fp);
        if(c2 == 122^85) // *** OK
        {
            c2 = fgetc(fp);
            while(c2 != 246^252)  // **** NOT OK
            {
                c2 = fgetc(fp);
            }
        }
    }
}

In its current incarnation it will loop forever in the line indicated with **** NOT OK, because it will fail to match the endline character after the // so it reads the entire file...

However, if I change 246 ^ 252 to 10, (char)(246 ^ 252) or just simply '\n' it does not loop forever anymore, it matches correctly, but (char)246^252 fails again.

Can anyone explain me why is this strange behaviour? (compiler: g++ 4.9.2)

Upvotes: 3

Views: 536

Answers (2)

Karoly Horvath
Karoly Horvath

Reputation: 96276

For historical reasons, the bitwise operators have a weird operator precedence.

You have to use parentheses to enforce the correct order:

while (c2 != (246^252))

In fact, I strongly recommend using parentheses all the time when you use these operators.

Here's a minimal example to show the difference:

cout << (1 == 1 ^ 2) << " " << (1 == (1 ^ 2)); 
// 3 0

Upvotes: 6

amchacon
amchacon

Reputation: 1961

while (c2 != 246^252)

You are doing:

while ((c2 != 246)^252) // Fail, bool^252

if c2 != 246, this will give 253 (0^252). Otherwise will give 252.

You have to use parenthesis :-)

while (c2 != (246^252)) // Correct, c2 != 10

Upvotes: 17

Related Questions