n=256;
converts the signed integer value 256
to uint8_t
, then assigns it to n
. This conversion is defined by the standard to take the value modulo-256, so the result is that n
is set to 0
.
Not sure where you can find a table, but the rules for integer conversions are at 6.3.1.3:
1 When a value with integer type is
converted to another integer type
other than _Bool, if the value can be
represented by the new type, it is
unchanged.
2 Otherwise, if the new type is
unsigned, the value is converted by
repeatedly adding or subtracting one
more than the maximum value that can
be represented in the new type until
the value is in the range of the new
type.49)
3 Otherwise, the new type is signed
and the value cannot be represented in
it; either the result is
implementation-defined or an
implementation-defined signal is
raised
As AndreyT points out, this doesn't cover what happens when an out-of-range value occurs during a calculation, as opposed to during a conversion. For unsigned types that's covered by 6.2.5/9:
A computation involving unsigned
operands can never overflow, because a
result that cannot be represented by
the resulting unsigned integer type is
reduced modulo the number that is one
greater than the largest value that
can be represented by the resulting
type.
For signed types, 3.4.3/3 says:
EXAMPLE An example of undefined behavior is the behavior on integer overflow.
(indirect, I know, but I'm too lazy to keep searching for the explicit description when this is the canonical example of undefined behavior).
Also note that in C, the integer promotion rules are quite tricky. Arithmetic operations are always performed on operands of the same type, so if your expression involves different types, there are a list of rules to decide how to choose what type to do the operation in. Both operands are promoted to this common type. It's always at least an int, though, so for a small type like uint8_t
, arithmetic will be done in an int
and converted back to uint8_t
on assignment to the result. Hence for example:
uint8_t x = 100;
uint8_t y = 100;
unsigned int z = x * y;
results in 10000, not 16 which would be the result if z were a uint8_t
too.
Also, is it acceptable to use C99's PRI* macros? How are they named?
Acceptable to whom? I don't mind, but you might want to check whether your compiler supports them or not. GCC does in the earliest version I have lying around, 3.4.4. They are defined in 7.8.1.
If you don't have a copy of the C standard, use this: http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf. It's a "draft" of the standard, released some time after the standard was published and including some corrections.