Sorry for the first answer, here is an explanation with C ++ standards :)
Is the output in any way predictable or is it undefined ??
This is predictable. There are two points in this code: First, the assignment of a value that the unsigned char type cannot contain:
unsigned char c; c = 300;
3.9.1 Basic types (Page 54)
Unsigned unsigned integers must obey the laws of arithmetic modulo 2n, where n is the number of bits in the value representation of this particular integer size. 41)
...
41) This means that unsigned arithmetic is not overflowing, because the result that cannot be represented by the unsigned integer type is equal to the reduced modulus number, which is one greater than the largest value that the unsigned integer type can represent by the result.
Basically:
c = 300 % (std::numeric_limits<unsigned char>::max() + 1);
Second, pass %d to the printf format printf to print the unsigned char variable.
This ysth got this right;) There is no undefined behavior, because the advertising conversion from unsigned char to int occurs in case of variadic arguments !
Please note: the second part of the answer is a rephrasing of what was said in the comments of this answer , but this is not my answer initially.
Arak
source share