how to test if three char variables are equal?

1
2
3
4
5

if (x == y == z) {
// do something
}


doesn't seem to work. i've printed each one out and even though they show the same character the if statement doesn't evaluate as true. am i doing something wrong or can i not evaluate three variables, and need to do something like

 
if (x=='a' && y=='a' && z=='a')

?

thanks!
You can't do it the first way, as C++ doesn't read it like you would first expect it to.

The second way should work fine and is how it normally done.
The problem here is that (x == y == z) is interpreted as ((x == y) == z) which effectively compares first two chars, which gives a boolean result and then compares that result to char z.This test might even pass, but it's definitely not you want.

If you want to test whether three variables are equal - you may write
 
if (x == y && y == z)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if( x == y && x == z  )

//Or

if( x == y && y == z )

//a function for this

template<typename T>
bool ifEqual(T a, T b, T c)
{
    return (a==b&&b==c); 
}
...
if( ifEqual<char>(x,y,z) )
It is enough to check that one of the variables is equal to other two.:) So this can be done in several ways.

if ( x == y && x == z )
or
if ( x == y && y == z )
or
if ( x == z && y == z )

Topic archived. No new replies allowed.