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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

operator && 2

Status
Not open for further replies.

TipGiver

Programmer
Sep 1, 2005
1,863
Hi,
take a look at this example:

Code:
#include <stdio.h>

int x;


int f()
{
  x=0;
  return x;
}

int g()
{
  x=4;
  return x;
}


void main()
{
  [b](void)(f() + g());[/b]
  printf("%d\n",x);
}

Running it as it is the printf will show 4
Changing '+' to '&&' gives 0.
If i change the f(): x=9, with '+' the result is 4 again.

Can you explain what the '&&' does?

I understand that '&' is for bits, so:
- if x=1, y=2 (binary 01 and 10) then x & y gives 0.
- ... same x && y gives 1.

Why ?


Thanks
 
That's very strange. I've never seen a line like:
Code:
(void)(f() && g());
but it probably works the same as:
Code:
if ( f() && g() )
What that is say is: if (f() != 0) AND (g() != 0) { do something }
It evaluates them in order from left to right, so if f() == 0, it doesn't execute g() because no matter what the result is, the whole condition failed.
If you used || on the other hand, it must always evaluate all conditions because even though f() == 0, g() might not equal 0, so it must execute g() to find out...

& and | are bitwise AND and OR operators,
&& and || are logical AND and OR operators.
 
so 0 is like false, 1 like true and what about the other numbers?? E.g 2, 3 ...?
 
Any non-zero number is intrepreted as true.

Note that the functions are evaluated left to right only when being used with logical operators. When you change && with + (an arithmetic operator) I believe there is no guarantee which function will be run first, and so the value that is output will depend on your compiler. Also note that the the result of the addition with + is ignored, so the last function called will set x.

Finally, to clarify what cpjust said, if you use || then the second function is called if the first returns 0, otherwise the second function will not be called and the entire expression will be true because the first function returned true.
 
Thanks both of you!
This 'chat' helped me alot
 
Another explanation:

&& and || are logical operators (AND and OR respectively), and both operands are interpreted as being binary.

In your code, f() result is FALSE because it returns zero and g() is TRUE because it returns 4 (C interprets non-zero results as a logical TRUE). So, a AND operation between FALSE and TRUE is always FALSE.

In the other hand, the || operator does a logical OR between 0 (FALSE) and 4 (TRUE), giving a result of 1 (TRUE).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top