Say we have an 8-bit unsigned integer n (UINT8_MAX=255); what is the behavior of the compiler for n=256? Where can I find a table of default behavior when the value of a data type is out of range for different data types? Is there a pattern to how they behave when set out of range?
#include <stdio.h>
#include <inttypes.h>
uint8_t n = UINT8_MAX;
int main() {
printf("%hhu ",n++);
printf("%hhu",n);
return 0;
}
Compiling with gcc -std=c99 -Wall *.c, this prints: 255 0
Also, is it acceptable to use C99’s PRI* macros? How are they named?
n=256;converts the signed integer value256touint8_t, then assigns it ton. This conversion is defined by the standard to take the value modulo-256, so the result is thatnis set to0.Not sure where you can find a table, but the rules for integer conversions are at 6.3.1.3:
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:
For signed types, 3.4.3/3 says:
(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 anintand converted back touint8_ton assignment to the result. Hence for example:results in 10000, not 16 which would be the result if z were a
uint8_ttoo.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.