spatara
spatara

Reputation: 901

C: conditional expressions with multiple operators

In C, is something like this legal?

if (0<=x<=y<=y+1) then ...

Or do I have to separate it with &&'s and ||'s and brackets?

Upvotes: 0

Views: 670

Answers (5)

NinjaDarth
NinjaDarth

Reputation: 393

It's an abuse of notation - even in a mathematical context and not strictly legal, even there. The only way to get the intended kind of meaning with <= still being a binary operator is (1) to lift the type of the operator from (ordinal,ordinal) → boolean to (boolean,ordinal), (boolean,ordinal) → (boolean,ordinal), with (B,Z) <= (B',Z') reinterpreted as (B && B' && Z <= Z', Z'), (2) to have an implicit conversion Z → (true, Z), and (3) to have another implicit conversion down to boolean (B, Z) → B.

You might be able to get something like that to happen in C++ with its tuple types, constructors and operator overloading.

Upvotes: 0

Serge
Serge

Reputation: 6095

This is completely legal but practically useless. You should build a proper expression with && and/or ||.

Upvotes: 1

Linuxios
Linuxios

Reputation: 35788

Nope, that is not at all possible to do what you want, although it is legal C code. You have to use && or ||. The reason is that you are actually seeing if, for example, y is greater then or equal to a Boolean, which in C and C++ is usually just 0 and 1.

Upvotes: 1

James
James

Reputation: 1371

It is legal (and defined; Google search term 'operator precedence'), but I don't think it will do what you expect or mean for it to do.

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

It's legal but probably doesn't do what you expect. It is treated as if you'd written:

if (((0 <= x) <= y) <= y+1)

The (0 <= x) evaluates to 0 or 1; the 0 or 1 is compared with y, yielding another 0 or 1 result; this is compared with y+1, yielding the final 0 or 1 used to control the if statement.

If you are aiming to ensure that x is not smaller than zero or bigger than y, and also to ensure that y is not bigger than y+1, then you'd write:

if (0 <= x && x <= y && y <= y+1)

I note that y <= y+1 is usually true. If y is an unsigned type and equal to the maximum value of that type, then y+1 is 0. If y is a signed type and equal to the maximum value of that type, then you invoke undefined behaviour by adding 1 to it. If you're lucky, y+1 will wrap to the maximum negative value for the signed type, but you can't rely on that (so maybe that makes it "if you're unlucky", because the bug won't necessarily show up before it causes major problems).

Upvotes: 7

Related Questions