Quick C Question

Retro2001

Senior member
Jun 20, 2000
767
0
0
It is my understanding that the following code segment (in C) is valid:

int a, b, c;
a = 1;
b = 1;
c = 1;
if (a == b == c)
printf("AT-HT");

This code, when run should print AT-HT. However, with the compiler my university uses, if a, b and c are set to -1, the IF statement is not taken. Is this a bug in the compiler or is it my misunderstanding of the C language?

Thanks and Peace,
Will
 

skriefal

Golden Member
Apr 10, 2000
1,424
3
81
No, I don't believe that code will work in the way you expect it to. The statement if (a == b == c) will be interpreted as if (a == (b == c)). Now, if b and c are both -1 then the inner (b == c) will evaluate to 1 (true). Thus, you now have if (a == 1) which is false since you said a is -1.

You should instead take advantage of the transitive relationship (think that's the correct term -- it's been a while since my college math courses!) and write your logic as if (a == b && b == c).

Minor note: I don't recall the exact order in which C parses operators. So instead of (a == (b == c)) if may instead read the statement as ((a == b) == c)). But the end result is still the same.
 

Sahakiel

Golden Member
Oct 19, 2001
1,746
0
86
I think skriefal is right, but the order is the second case. It becomes (a==b)==c. From what I remember of my CS classes, the boolean operations actually call standard class libraries. I think the operand == is evaluated with the left side as a int variable and the right side as a boolean variable, or something like that. That allows you to string together a series of comparisons ad infinitum the same way you can string together << operands. If I remember correctly, the right side of the << class definition is a ostream variable, which is the key to allowing a series of << statements.
My $0.02
 

Retro2001

Senior member
Jun 20, 2000
767
0
0
Thanks for the prompt replies. I just tossed down some new and differant code and it is a matter of the grouping. The fact that I had been testing with 1 and -1 caused the confusion, as the if statment worked with the 1's.

Thanks and Peace,
Will
 

bobdavis

Junior Member
Feb 25, 2001
4
0
0
If you want the same effect as you wrote in your earlier post, use the and operator, &&.

int a = 1, b = 1, c = 1;
if (a == b && b == c) // if a = b AND b = c, then
printf("AT-HT"); // printf

If you want to OR two boolean values together, use the || operator.