• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Quick C Question

Retro2001

Senior member
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
 
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.
 
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
 
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
 
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.
 
Back
Top