Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is multiple variable comparision inline undefined behavior?

I was telling a friend of mine (which is learning C) that he couldn't do multiple variables comparision at once:

int main(){
    int a[4];

    scanf("%d %d %d %d", &a[0], &a[1], &a[2], &a[3]);

    if(a[0] < a[1] < a[2] < a[3]){
        printf("OK!\n");

    }

    else{
        printf("I've told ya\n");

    }

}

So, to prove I was right I've coded the program above and then I've executed it with 1 2 3 4. Surprisingly it printed OK!. And so I didn't know what to tell him, because I was sure it wasn't right.

Finally, is it or is it not undefined behavior?

like image 466
Rodrigo Siqueira Avatar asked Jan 30 '13 20:01

Rodrigo Siqueira


1 Answers

No, it's well-defined. It simply has different semantics to what you're expecting.

The expression is evaluated as follows:

if (((a[0] < a[1]) < a[2]) < a[3]) {

Each comparison produces a boolean (0 or 1) outcome.

The (boolean) result of a[0] < a[1] is compared to a[2], and the (boolean) result of that comparison is compared to a[3].

I am sure there are some legitimate use cases, but they are rare at best.

The correct way to express what you're trying to express is

if (a[0] < a[1] && a[1] < a[2] && a[2] < a[3]) {
like image 79
NPE Avatar answered Nov 15 '22 08:11

NPE