In the C language, expressions often involve type conversions (type promotion, type conversion) governed by the standard:
char, short) are automatically promoted to int or unsigned int before arithmetic operations.Example:
unsigned short a = 65535; signed short b = -1; printf("%d ", a + b); // depends on conversion!
Recommendation: pay close attention to operand types, especially when working with bitwise operations, array lengths, indexes, and avoid implicit mixing of signed and unsigned types.
What will the following fragment output?
unsigned int u = 1; int i = -2; printf("%d ", u + i);
Answer: The variable i will be converted to unsigned int, the final value will become very large, since the underlying result is: 1U + (unsigned int)-2U, which will yield a number close to UINT_MAX (4294967295). A negative number will be printed only if printf is formatted as int, otherwise garbage will be shown.
Story
In the calculation of average pixel intensity,
intandunsigned intwere confused. Negative values were incorrectly translated through unsigned, yielding large numbers, leading to image buffer overflow.
Story
In embedded firmware, string length was calculated using
size_t, while array indexing was done usingint. When checking the condition for array bounds,int i >= size_t lenwas compared, breaking the logic for long strings and causing bugs when comparing different types (size_t is unsigned).
Story
A developer on a financial project calculated the remainder for negative numbers using
%, forgetting that the sign of the result for negative operands depends on the implementation. In one environment, the result was positive, in another — negative, causing calculations to "shift" periodically.