Yes, the same rule applies for C++. (However, I am going by a 2010 draft of the C++ standard; C++ 2003 is old. Also, I am using N3092, not the official draft.) Clause 4.9, paragraph 1 says “The behavior is undefined if the truncated value cannot be represented in the destination type.”
Unsigned integer arithmetic does wrap; it is performed modulo 1 more than the maximum value of the type. However, this applies to arithmetic within the type. Conversion from floating-point to unsigned integer is not part of this.
Your code for converting d2
seems more complicated than necessary. If d2
is within the range of an int
, you could simply use unsigned char c2 = (int) d2;
. (Although conversion from int
to unsigned int
is also outside homogeneous unsigned integer arithmetic, the specification for this conversion does say it is reduced the same way unsigned integer arithmetic is.)