Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (val1 > val2 > val3) a valid comparison in C? [duplicate]

Tags:

c

I was messing around a bit in C while making a function, and somehow ended up with a comparison like this:

if (sizeAllocated > type_get_binary_size(data) > spaceAvailable)

The (for me) unexpected thing was that this compiled without so much as a warning (using IAR compiler for ARM, C99 standard with IAR extensions).
This doesn't look like it should be valid C (at least it's not a valid comparison in any other languages I can think about at the moment), can some gurus help me shed some light on whether this is some IAR-specific quirk or if it's actual standard C that's just too obscure to be included in any common tutorials?

like image 348
ToVine Avatar asked Jan 24 '26 17:01

ToVine


2 Answers

This is valid code, but it won't do what you expect.

The > operator is left-associative, so the expression effectively becomes:

((sizeAllocated > type_get_binary_size(data)) > spaceAvailable)

The inner portion will evaluate to 0 if the condition is false or 1 if the condition is true. This value is then compared against spaceAvailable.

In C, the results of a comparison operator have an integer type, so comparing this result to an integer is valid.

So what you're actually doing is either 0 > spaceAvailable or 1 > spaceAvailable, depending on how the first conditional evaluates.

What you probably want is this:

int size = type_get_binary_size(data);
if ((sizeAllocated > size) && (size > spaceAvailable))

Note that the function call is done first before the if so it isn't called twice in the conditional.

like image 88
dbush Avatar answered Jan 26 '26 09:01

dbush


The > operator is left-associative, so A > B > C is parsed as (A > B) > C. A > B evaluates to 0 or 1, so you're basically comparing 0 > C or 1 > C.

like image 45
John Bode Avatar answered Jan 26 '26 10:01

John Bode



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!