I want to know if:
val1 = val2 = val3 ... = val6
I try this:
if (val1 == val2 == val3 == val4 == val5 == val6)
{
}
but it don't work, why?
The ==
operator only works between pairs of values. When you do this:
val1 == val2 == val3
What's really happening is this:
(val1 == val2) == val3
So if val1
and val2
are equal, the expression in the parenthesis evaluates to true:
true == val3
And then it checks whether true
== val3
, not whether val1
or val2
== val3
. You have to do this instead:
val1 == val2 && val1 == val3
This is getting pretty unwieldy for six variables though. Do you really have six local variables that you have to compare? Perhaps you should store them in an array of some sort. Then you can do:
bool all_equal(int *vals, int length) {
if (length == 0) {
return true;
}
int first = vals[0];
for (int i=1; i < length; i++) {
if (vals[i] != first) {
return false;
}
}
return true;
}
So instead of:
int val1 = ..., val2 = ..., val3 = ..., val4 = ..., val5 = ..., val6 = ...;
if (val1 == val2 && val2 == val3 && val3 == val4 && val4 == val5 && val5 == val6) {
...
}
You would to:
int vals[6] = {..., ..., ..., ..., ..., ...};
if (all_equal(vals, 6)) {
...
}
You can't chain the ==
operator. Do this:
if (val1 == val2 && val2 == val3 && val3 == val4 && val4 == val5 && val5 == val6) {
// they are all equal
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With