[try Beta version]
Not logged in

 
An if, else with multiple conditions.

Jan 14, 2014 at 8:38pm
I'm having some issues with multiple conditions in an if statement that I'm writing.

It will compile but my functions fail, I want it to achieve else when any one of the condition are the same as the loop counter.

Everything seems fine when there is only one condition to be true. So what is wrong with my structure?

My code:
1
2
3
4
if ( Number1[loop1] != 1 || 2 || 3 ){
}
else {
}                   

I also tried:
1
2
3
4
if ( loop1 != 1 || 2 || 3 ){
}
else {
}                   

And:
1
2
3
4
if ( loop1 != 1 || loop1 != 2 || loop1 != 3 ){
}
else {
}                   


I'm compiling in C but if im correct this should compile the same in C++?
Jan 14, 2014 at 9:11pm
the first two are wrong (the syntax is correct but if(Number1[loop1]!=1||2||3 is equivalent to
((Number1[loop1]!=1) or 2 or 3) and not ((Number1[loop1]!=1) or (Number1[loop1]!=2) or (Number1[loop1]!=3)) so it is always equal to true because 2!=0
as for the last one it seems correct but (I don't know what you mean by Number1[loop1] or loop1) I assume since it didn't work that it should be
1
2
3
4
if ( Number1[loop1] != 1 || Number1[loop1] != 2 || Number1[loop1] != 3 ){
}
else {
}
Last edited on Jan 14, 2014 at 9:12pm
Jan 14, 2014 at 9:22pm
Let's look at what you have right now:
1
2
if ( Number1[loop1] != 1 || 2 || 3 ){
}

With some parenthesis, this is essentially the same as
1
2
if ( (Number1[loop1] != 1) || (2) || (3) ){
}

Now, since anything non-zero evaluates to true, this is basically the same as
1
2
if ( (Number1[loop1] != 1) || true || true ){
}

This, of course, is always true.

Your last code is closer:
1
2
if ( loop1 != 1 || loop1 != 2 || loop1 != 3 ){
}

But remember that for a logical OR expression to be true, you only need one of the operands to be true, so this will also always evaluate to true.
(think: "I want a number that's either:
1) Not equal to 1, or
2) Not equal to 2, or
3) Not equal to 3."
Every number has that property!)

In short, to get what you want, use this:
1
2
if ( loop1 != 1 && loop1 != 2 && loop1 != 3 ){
}

(think: "I want a number that's
1) Not equal to 1, and
2) Not equal to 2, and
3) Not equal to 3."
Make more sense now?)

(Now, I'm not sure what Number1 is or why it's not in your other two attempts, so I'll just leave it to you to figure out whether you need that or not.)

400!
Jan 14, 2014 at 9:23pm
@long double main
1
2
if ( loop1 != 1 && loop1 != 2 && loop1 != 3 ){
}

I missed that part
Topic archived. No new replies allowed.