Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A question of syntax 2

Status
Not open for further replies.

biot023

Programmer
Nov 8, 2001
403
0
0
GB
Hallo.
Would someone be able to tell me the difference between these two pieces of code?

if(a==b || a==c)
//whatever

if(a==b | a==c)
//whatever


I seem to think that the second example will only test the second argument (a==c) if the first (a==b) proves false.
Is this correct?
I can't remember where I came across this, but it would be immensely useful if true.
Cheers,
Douglas JL

A salesman is a machine for turning coke into obnoxious arrogance.

Common sense is what tells you the world is flat.

 
The first is a logical or while the second is a bitwise or. I know that when an if statement uses a logical and (&&) the statement stops if the first statement is false. I've never read anything about the ors.

James P. Cottingham
[sup]
There's no place like 127.0.0.1.
There's no place like 127.0.0.1.
[/sup]
 
>> I seem to think that the second example will only test the second argument (a==c) if the first (a==b) proves false.

Actually you have it backwards. Most modern compilers perform boolean short-circuit optimizations, thus once the result of the boolean expression is known, the rest of the expression need not be evaluated. Like 2ffat explained for the logical and, logical or's are also short-circuited.

So in your example above: if (a==b || a==c), if (a==b) is true, then (a == c) isn't evaluated.

On the other hand for the bitwise or: (a==b | a==c) the full expression must be evaluated, because it is a bitwise operation, not a boolean expression. If it isn't clear what a bitwise operation is, maybe do some research or ask again.

Hope this helps.
 
Thanks alot, that helps clear it up.
Now I know why my code was working like I wanted it to (always nice)!
I shall go & invstigate bitwise operations...
Cheers,
DJL

A salesman is a machine for turning coke into obnoxious arrogance.

Common sense is what tells you the world is flat.

 
I had this give me an error in my program today.

I had

if (FirstRun || NewHalfHour())
DoTargets();

The only thing is, that in NewHalfHour() I have

if (FirstRun)
initialize stuff;

Do What normally happens

So my stuff in NewHalfHour never got initialized and gave me access violations in the end.

Changing it to
if (NewHalfHour() || FirstRun)
did the trick, though changing || to | would have worked too.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top