C Language | Introduction to C | Type Casting

This article explains how C converts values when expressions use different data types.

Arithmetic Conversions

When an expression combines different arithmetic types, C converts operands to a suitable common type. Smaller integer types are promoted to int, and mixed expressions generally convert values toward a type that can represent a wider range.

Code 1

#include <stdio.h>

int main() {
 char chVar = 50;
 int iVar = 100;
 float fVar = .555;

 printf("%g\n", chVar + iVar + fVar);
 return 0;
}

The expression combines char, int, and float values and prints 150.555.

Assignment Conversions

Assigning a value to a variable of another type also performs an implicit conversion. Widening conversions usually preserve information.

char chVar = 100;
int iVar = chVar;

Narrowing conversions may lose information.

int iVar = 0xABCD;
unsigned char chVar = iVar;

If unsigned char is eight bits, the second example stores only the low eight bits and produces 0xCD. Converting a floating-point value to an integer discards the fractional part.

Explicit Type Casting

Use a cast when the conversion should be explicit.

(target-type)value

Code 2

#include <stdio.h>

int main() {
 float fVar = 12.34f;
 printf("value = %g\n", fVar);
 printf("integer = %d\n", (int)fVar);
 printf("fraction = %g\n", fVar - (int)fVar);
 return 0;
}

Casts are useful, but narrowing conversions should be used carefully because they can discard data.