As long as a is not too large to fit inside a regular int? Or will
this lose some data or something?
Note: actually your question is more C than C++. To add a C++
specific note, consider using static_cast<>, reinterpret_cast<>
and the like instead of the 'automagic' C cast. The C++ form
allows you to specify exactly what you want to achieve, thus
enabling better diagnostics from the compiler.
Casting if the target is large enough for the number will always
work. If it is not, it will still 'work', but the result is
unspecified. I.e. this works without problem (on a compiler that
supports long long, as do at least GCC and VC++):
unsigned long long val1 = 10;
char val2 = static_cast<char>(val1);
but the result of this is another matter:
unsigned short x = 16384;
unsigned char y = static_cast<unsigned char>(x);
I think the standard specifies for integer casts that the number
is 'capped' on a bit level. Usually, the above example will thus
yield y==0, since 16384==100000000000000b;
However just casting from signed to unsigned is (IIRC)
guaranteed to work even without loss of data, meaning that for
any int 'x' the following holds true:
static_cast<int>(static_cast<unsigned>(x)) == x
This even works if for example x is negative. In that case
though there's a another caveat: the semantics of interpreting a
negative number as unsigned are AFAIK implementation-defined.
The sizes of most base types (and AFAIK even the exact bit
representation format of a neg. number) are not enforced by the
standard (it only specifies constraints on value ranges), so one
has to be extra-careful.
Regards,
Robert