Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

figuring out integer comparison in C

Tags:

c

I'm just wondering how does boundary checking works in the following case.

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int x = 0; x < 3; x++) {
                printf("%d < %d < %d is %d\n", i, x, j, i < x < j);
            }
        }
    }
    return 0;
}

I tried right-to-left/left-to-right precedence but it doesn't seem to work. (not too sure about it though, maybe it does?)

I think this is undefined behaviour and using && would probably be easier than figuring this out but I'm quite interested in how the logic behind this works. Would appreciate if anyone could help explain this or point me towards the right direction

edit: Thanks for all the help! got the answer I needed. This must seem completely trivial to all of you but it really made many things I thought about in the past few days clicked. Really appreciate the time you guys took to help me out. Thanks again!

like image 682
David Avatar asked May 01 '26 19:05

David


1 Answers

i < x < j is perfectly well-defined, but it doesn't do what you think it does.

It's equivalent to (i < x) < j, due to the associativity of <.

But (i < x) is either 0 or 1, as that's how the relational operators are defined in C.

So, for example, if j is greater than 1, then i < x < j is always 1.

Consider writing i < x && x < j instead.

like image 137
Bathsheba Avatar answered May 03 '26 09:05

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!