Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a lot of int is equal

Tags:

c

ios

objective-c

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?

like image 764
Anis Avatar asked Oct 11 '13 16:10

Anis


2 Answers

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)) {
    ...
}
like image 141
Claudiu Avatar answered Sep 30 '22 05:09

Claudiu


You can't chain the == operator. Do this:

if (val1 == val2 && val2 == val3 && val3 == val4 && val4 == val5 && val5 == val6) {
    // they are all equal
}
like image 41
rmaddy Avatar answered Sep 30 '22 06:09

rmaddy