This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Integral conversions in C/C++
- From: Christian BÃhme <monodhs at gmx dot de>
- To: gcc-help at gcc dot gnu dot org
- Date: Sun, 20 Apr 2008 03:57:32 +0200
- Subject: Integral conversions in C/C++
Hi all,
I ran into a problem with an expression that I imagined is too
trivial to even needing a second thought in the first place.
However, on a 32 bit machine, the code
--->8---
#include <stdint.h>
// ...
int64_t a;
uint32_t b = 8;
a = -(b * 2u);
--->8---
assigns a the value 0xfffffff0 while no warnings were issued even
when compiling with all warnings (-Wall) switched on. Strangely
enough and for reasons escaping me
--->8---
#include <stdint.h>
// ...
int64_t a;
uint32_t b = 8;
a = -((int64_t )(b * 2u));
--->8---
produces the expected value of 0xfffffffffffffff0 (or -16).
The destination type (ie, a's type) is the same in both versions
which is large enough to hold the result of the RHS of a = -(x)
with x being a temporary variable for the result of the sub
expression (b * 2u). In order to represent the latter's result,
its destination type clearly cannot be that of its operands and
must be converted to a larger type. Since a's type satisfies
these requirements already, it seems logical to assume that x
is defined with this type also which clearly is not the case
with the first version. Having 4.7 of the ISO C++ standard
in mind which deals with integral _conversions_ (as opposed
to integral _promotions_) at which point may I be missing
something here ? Where's the logic in having to insert a
type cast for a temporary when it can be unambiguously inferred
from the destination type of the expression ? Is this an
``implementation detail'' ?
Cheers,
Christian