I'm in the process of teaching myself C++ with the book Accelerated C++, on chapter 3. But I was wondering if I could shorten this if else code. Is there a simpler way to do that? I wrote this up just now after having the idea at work. I don't really like all of the if's and else's.
if (target != 1,2,3,4,5) You don't really need this if because you know that target can't be any of 1, 2, 3, 4 or 5 because you have checked that above.
else and if after each other is often written on the same row.
isn't checking that target doesn't equal 1, 2, 3, 4, or 5
It's checking that target isn't one and then applying the comma operator (aka sequence operator) to evaluate your other "expressions", which being just numbers don't do enything. http://www.cplusplus.com/doc/tutorial/operators/
To test that target is not 1, 2, 3, 4, or 5 you need
if (target != 1,2,3,4,5)
to make it simple, comma operator are evaluated from left to right
(http://www.cplusplus.com/doc/tutorial/operators/)
"if" statement will evaluate last condition, in this example is 5.
in c++, any integer value except 0 considered true.
cmiiw
Thanks everyone. i forgot about the && operator. I won't make that same problem with the last if else again. But I like peter's array solution. I haven't learned about switches or arrays yet but it beats the way i was doing this. Turns out I didn't learn about comma operators yet either so that explains my mistake lol.