-1

Hi I have these two separate if statements, when put like so ;

if (powerlevel <= 0) // <--- ends up having no effect
if (src.health <= 0)
    the_thing_to_do();

How do I combine these two if statements into one? is it possible? If so how?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
user2621004
  • 15
  • 1
  • 2
  • 5
    Any learning resource should tackle this pretty soon after if statements. – chris Jul 26 '13 at 02:01
  • What do you mean by "ends up having no effect" ? – amdn Jul 26 '13 at 03:09
  • Just out of curiosity, what effect will the first statement have? Due to the lack of {}'s, it will only effect the second if statement, right? Not the_thing_to_do? – PunDefeated Jul 26 '13 at 07:17
  • @PunDefeated: the_thing_to_do is controlled by the second if statement, so the first if powerlevel test controls it (and any else statement that might follow it). In other words, the two ifs effectively form a logical and "&&", such that the_thing_to_do is only done if neither variable is positive. – Tony Delroy Jul 27 '13 at 01:40

5 Answers5

6

If you want both statements to be true use logical AND

if(powerlevel <= 0 && src.health <= 0) 

If you want either of the statements to be true use logical OR

if(powerlevel <= 0 || src.health <= 0) 

Both of the above operators are logical operators

GWW
  • 43,129
  • 11
  • 115
  • 108
4

Use operator&& if you want both of them to be met (logical AND)

if(powerlevel <= 0 && src.health <= 0) { .. }

or operator|| if you want just one to be met (logical OR)

if(powerlevel <= 0 || src.health <= 0) { .. }
Rapptz
  • 20,807
  • 5
  • 72
  • 86
4

It depends if you want both to evaluate to true...

if ((powerlevel <= 0) && (src.health <= 0)) {
  // do stuff
}

... or at least one ...

if ((powerlevel <= 0) || (src.health <= 0)) {
  // do stuff
}

The difference being logical AND (&&) or logical OR (||)

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
atk
  • 9,244
  • 3
  • 32
  • 32
1

Or if you don't want to use && you can use a Ternary Operator

#include <iostream>

int main (int argc, char* argv[])
{
  struct
  {
      int health;
  } src;

  int powerlevel = 1;
  src.health = 1;

 bool result((powerlevel <= 0) ? ((src.health <=0) ? true : false)  : false);

 std::cout << "Result: " << result << std::endl;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
bjackfly
  • 3,236
  • 2
  • 25
  • 38
  • I really like ternary operators, but `(x ? true : false)`...? Yikes! ;-) – Tony Delroy Jul 26 '13 at 04:03
  • Yeah its a little much I agree but others already suggested the && version and I thought I would just introduce him to the concept since he was asking for a way to do it in a single line. – bjackfly Jul 26 '13 at 18:02
1

Just an aternative if it is meaningful(sometimes).

Both true:
if (!(src.health > 0  || powerlevel > 0)) {}

at least one is true:
if (!(src.health > 0  && powerlevel > 0)) {}
lulyon
  • 6,707
  • 7
  • 32
  • 49