ToVine ToVine - 1 year ago 122
C Question

Is (val1 > val2 > val3) a valid comparison in 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?

Answer Source

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.