C:C Type Casting: Explicit Type Conversion with Examples
C•Type Casting

C Type Casting: Explicit Type Conversion with Examples

Learn how to avoid integer division truncation, convert characters to ASCII values, and cast numeric types.

Syntax

target_type variable = (target_type) original_value;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
(type)Cast OperatorExplicitly converts expression to target type.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>

int main(void) {
    int sum = 175;
    int count = 4;

    // Explicit cast prevents integer truncation
    float average = (float)sum / count;

    printf("Sum:     %d\n", sum);
    printf("Count:   %d\n", count);
    printf("Average: %.2f\n", average);

    // ASCII conversion
    char letter = 'K';
    int asciiValue = (int)letter;
    printf("Character '%c' has ASCII code: %d\n", letter, asciiValue);

    return 0;
}
Expected Output:
Sum:     175
Count:   4
Average: 43.75
Character 'K' has ASCII code: 75

How It Works: Step-by-Step

  • Line 8: (float)sum casts sum to float before division occurs.
  • Lines 15-17: Converts char literal to its underlying ASCII code.

Key Concepts

  • In expressions with mixed types, C promotes smaller types to larger types automatically.
  • Casting one operand in a division causes floating-point division to occur.

Common Mistake: Casting after the integer division has already occurred

(float)(a / b) truncates the integer division first, then converts the truncated result.

❌ Incorrect
float avg = (float)(175 / 4); // Evaluates 175/4 = 43, then casts to 43.0!
✅ Correct
float avg = (float)175 / 4; // Promotes to float first: 43.75

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler