Arithmetic addition with strange results

D

dizzy

Hello

I have noticed a strange behavior (tho for many of you this is to be
expected I'm sure :) ) when I have an expression that adds a long
value with an unsigned one (like in "10l + 10u").

On 32bit platforms (where unsigned can represent more than long) the
result is of unsigned long type while on 64bit platforms the result is
of long time.

Usually in my coding experience I've learned that when writing bool
expressions like "a - 10 < b" I should better write them "a < b + 10"
because somehow I thought this keeps the expressions to their original
types (I thought "b + 10" will have the type of "b") and then the case
of comparing signed to unsigned values depends if a and b were mixed
signed types. It seems that was false.

Can someone point me to the relevant standard section that
allows/requires that behavior described above?

Thank you!
 
J

James Kanze

Just search (the standard) for "usual arithmetic conversions"
and "promotion".
And yes, the type of an expression depends on the ranges of
types with the particular C++ compiler, and so does the type
of a literal! :)

Right. In particular, don't mix signedness. Ever. If you're
stuck with a value which is signed, and another which isn't,
cast one of them to ensure that both have the same signedness.
(The exception is small non-negative values. You can safely use
integral literals like 0 and 1 with unsigned types, even though
they are formally signed. But that's about it.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top