ProgrammingC Developer

What type conversion (type conversion, type promotion) rules are applied in expressions in the C language? Provide examples of unexpected errors and solutions.

Pass interviews with Hintsage AI assistant

Answer

In the C language, expressions often involve type conversions (type promotion, type conversion) governed by the standard:

  • Integer Promotion: lower-width types (e.g., char, short) are automatically promoted to int or unsigned int before arithmetic operations.
  • Usual Arithmetic Conversions: if the operands are of different types, they are converted to a "wider" type according to specified rules.
  • In mixed operations with signed and unsigned types, the result may unexpectedly change due to conversion.

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.

Trick Question

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.

Examples of real errors due to ignorance of the nuances of the topic


Story

In the calculation of average pixel intensity, int and unsigned int were 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 using int. When checking the condition for array bounds, int i >= size_t len was 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.