-1

I was reading this post i am wondering why anyone would care to test the second condition if the first is false

eg:

boolean a =false;
if(a && b) //do soemthing

Why would you test if b is false?

Community
  • 1
  • 1
124697
  • 22,097
  • 68
  • 188
  • 315

5 Answers5

1

Single & is a bitwise operator, so that's what you use it for. For instance, if you wanted to check if a bit is set:

unsigned int bit = 4;
if (bit & value) {
    //third lowest bit is set
}

This happens a lot in C library functions. It's really useful if you're conserving memory and using individual bits rather than separate variables.

EDIT: I misread the post a bit. I see the context you are talking about now. So to agree with the others, only if b has a side effect.

GJK
  • 37,023
  • 8
  • 55
  • 74
0

It could make sense if for example you have a function which does something that you want to get fired, regardless of what the first value is.

if( a & _checkForB())
puelo
  • 5,464
  • 2
  • 34
  • 62
0

The only case I can think of is where the evaluation of the second has some desirable side effect.

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
0

I don't know whether this is the actual use, but sometimes you have code acrobatics such as

string s;
if((s = reader.read()))
{
    doStuff
}

and i suppose you can use the &, if you had multiple things in your condition that did stuff.

0

Why would you test if b is false?

I guess you mean:

Why would you test b if a is false?

E.g. if b has a side effect. Though you probably have a design issue in this case.

In practice, "&" is not used for booleans except maybe "&=".

Puce
  • 37,247
  • 13
  • 80
  • 152