cellka
cellka

Reputation: 129

Signed and unsigned integers with logical operators

int x = /* some integer */; 
unsigned int ux = (unsigned) x;

we have

x >= 0 || x < ux

we know that in x < ux the first x is cast implicitly to unsigned but is the first x in x >= 0 (1) cast to unsigned implicitly?

Upvotes: 1

Views: 924

Answers (3)

No. It happens operator by operator.

x >= 0 || x < ux

is naturally

(x >= 0) || (x < ux)

Since x and 0 are both ints, there is no need for any (usual arithmetic) conversions...

And even though x is converted to unsigned in x < ux, the value of the expression x < ux is of type int - either 0 or 1 (just like on the the left-hand side).

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234715

No it isn’t.

This is because x >= 0 is an expression. (Formally 0 is an octal constant of type int.)

Try 1 / 2 * 1.0 for a more pernicious example. This is grouped as (1 / 2) * 1.0 and is zero since the integers in the expression 1 / 2 are not promoted to floating point.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224944

No, 0 is an int, so there are no promotions in the x >= 0 part of your expression.

Upvotes: 0

Related Questions