• Home
  • 4.3 Integer Conversion

4.3 Integer Conversion

View Categories

4.3 Integer Conversion

Integer conversion occurs when a value of one integer type is converted to another integer type. The result depends on the destination type and whether it can represent the original value.

#include <stdio.h>

int main(void)
{
    int number = 130;
    signed char small = number;
    unsigned int positive = -10;

    printf("Original: %d\n", number);
    printf("Converted: %d\n", small);
    printf("Unsigned: %u\n", positive);

    return 0;
}

Example Output #

On a typical implementation with 8-bit signed char using two’s-complement representation and 32-bit unsigned int:

Original: 130
Converted: -126
Unsigned: 4294967286

Explanation #

The assignment:

signed char small = number;

converts the value 130 to signed char. If the destination type cannot represent the original value, the result is implementation-defined in C17 and earlier. C23 specifies the result differently. The example output reflects a common implementation.

The assignment:

unsigned int positive = -10;

converts -10 to unsigned int. Unsigned integer conversion produces the value congruent to the original value modulo one more than the maximum value of the destination type.

For a 32-bit unsigned int, the result is:\[ 2^{32}-10 = 4294967286 \]

Integer Conversion Rules #

Conversion Behavior
Smaller value to a wider integer type that can represent it Value is preserved
Signed integer to unsigned integer Result is reduced modulo one more than the unsigned maximum
Unsigned integer to a signed integer type that can represent the value Value is preserved
Value outside the destination signed type’s range Result depends on the applicable C standard
Wider integer type to a narrower type Value may change if it is not representable

Integer conversions can change a value even when no arithmetic operation is performed. The destination type determines how the converted value is represented.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *