Question Details

No question body available.

Tags

c language-lawyer

Answers (1)

Accepted Answer Available
Accepted Answer
May 31, 2026 Score: 3 Rep: 46,072 Quality: Expert Completeness: 60%

For the examples given, assume CHARMAX == 127

C89:

§6.2.1.2 Signed and unsigned integers

When a value with integral type is demoted to a signed integer with smaller size, or an unsigned integer is conveted to its corresponding signed integer, if the value cannot be repesented the result is implementation-defined.

(char) (int) 128 and (char) (unsigned char) 128 would be implementation-defined.

C99/C11/C17/C23:

§6.3.1.3 Signed and unsigned integers

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.

Otherwise, if the new type is unsigned, [...].

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.

(char) (int) 128 and (char) (unsigned char) 128 would be implementation-defined or raises a signal.

The current C2y draft has the same wording except _Bool -> bool.

There is no special wording for char/signed char/unsigned char


So yes, you need special handling for maximum portability. However, on most implementations, simply casting will do what you need.

I don't think POSIX defines what happens for this, leaving it implementation defined. POSIX does mandate twos-complement, so you can memcpy/union cast.