C Programming Basics
A program that sets "char c = 200;" and prints c with %d in printf printed −56 when compiled and run with gcc for x86-64 Linux, and 200 with gcc for Arm Linux. Which of the following is the reason for the difference?
- AArm is big-endian, so the bytes are read in reverse order
- BWhether a char without signed or unsigned is signed or unsigned is decided by the implementation; it is signed on x86-64 and unsigned on Arm
- Cchar on x86-64 is 16 bits, and its upper bit is treated as the sign
Show answer and explanation
Answer: B. Whether a char without signed or unsigned is signed or unsigned is decided by the implementation; it is signed on x86-64 and unsigned on Arm
Whether a char without signed or unsigned is signed or unsigned is not fixed by the standard but left to the implementation (implementation-defined). On x86-64 Linux, char is signed and can only represent −128 to 127, so storing 200 gives 200 − 256 = −56. On Arm and RISC-V Linux, char is unsigned and 200 is stored as is. When handling byte data, use unsigned char or uint8_t to make the signedness explicit.
- A. Arm Linux is generally little-endian, and byte order does not affect the value of a 1-byte char.
- B. Correct. The signedness of char is implementation-defined: signed on x86-64 and unsigned on Arm Linux.
- C. char is 1 byte in every implementation, and 8 bits on x86-64.