Even or Odd

closed account (10oTURfi)
In C++ Beginners Guide by Herbert Schildt program tests if number is even like this:

1
2
3
4
5
#define EVEN(x) (x)%2==0 ? 1 : 0
//...
	if(EVEN(x)) cout << "Even!" << endl;
	else cout << "Odd!" << endl;
//... 


But I dont understand what does ? 1 : 0 mean.
If I remove that part of code program will still work as intended.

#define EVEN(x) (x)%2==0 //? 1 : 0

Can anyone explain that please?
This here they explain http://en.wikipedia.org/wiki/%3F:
Yes. I think if you remove the part it still works, as in this case the command just returns the value of (x) % 2 == 0, which is exactly the value 1 (if true) and 0 (if false), but the meaning of the commands are different.
closed account (10oTURfi)
Yes! This was what I was looking for. Thanks.
(condition) ? (value1) : (value2) is a test expression that returns value1 if condition is true, or value2 if condition is false.

It still works when you remove it because (x)%2==0 will evaluate to true for even numbers, which will then be given to if(EVEN(x)) on line 3, which makes the if statement go down the true branch. In this case, the ? 1 : 0 is not neccassary, because all it does it return true for a true value, and false for a false value. In any other case it would be neccassary however.
Topic archived. No new replies allowed.