Quick C Question

Hang out, sip some ice tea, and shoot the breeze with TR regulars.

Moderators: emkubed, Captain Ned

Postposted on Sat Apr 06, 2002 9:59 pm

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
Max: "It seems these evil men will never begin to understand our peaceful nature."
Sam: "Hope they figure it out pretty quick. My trigger finger is blistering."
-- Sam & Max, the Freelance Police
Prelude
Gerbil
 
Posts: 52
Joined: Fri Jan 04, 2002 7:00 pm
Location: Mizzou

Postposted on Sat Apr 06, 2002 10:47 pm

Try adding a newline, and breaking out the tests:

main()
{
int a = 1, b = 1, c = 1;

if ((a == b) && (b == c))
    printf("AT-HT\n");
}

_________________
You are false data.
Speed
Gerbil Elite
 
Posts: 706
Joined: Thu Dec 27, 2001 7:00 pm
Location: Chicago, IL USA

Postposted on Sun Apr 07, 2002 12:46 am

AAHHHH NO!!!!!!!!
Borland C++ FLash backs from high school.

From what I remember leaving out the "MAIN()" and the "{,}" can cause strange things like that to occur.
Toyotamr2_86NA
Gerbil Team Leader
 
Posts: 212
Joined: Fri Feb 01, 2002 7:00 pm

Postposted on Sun Apr 07, 2002 1:41 am

Prelude - that's quite a simple one, and the reason is due to this: The expression is broken down into two components that are evaluated left to right (I think, I never bothered to learn C's precedent rules):

((a == b) == c)

In your compiler's case the first truth test "a == b" will probably evaluate to 1 if true and 0 if false. So the expression is reduced to ((1) == c) if a was equal to b (which it was, because they're both 1). Then, because c is -1, the expression "((1) == c)" is obviously not true, so it comes up false.

It only worked with all the variables being 1 because that happened to co-incide with the truth value for your compiler which is also 1.

Truth operators are a bit funny to get used to in C, :roll: , so try to deal with them on their own terms :) - in other words, use (a == b && b == c).

Cheers,
creepy_hand
creepy_hand
Gerbil In Training
 
Posts: 6
Joined: Wed Mar 06, 2002 7:00 pm


Return to The Back Porch

Who is online

Users browsing this forum: No registered users and 3 guests