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:
| Parameter | Type | Description |
|---|---|---|
| (type) | Cast Operator | Explicitly converts expression to target type. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C Primitive Data Types and Explicit Format Specifiers
Master C primitive types (int, float, double, char, unsigned long), sizeof memory allocation, and explicit printf format specifiers.
C Operators: Arithmetic, Relational, and Bitwise Logic
Master C operators including arithmetic, bitwise shifts, modulus, and logical boolean checks.
C Short-Circuit Ternary Logic and Conditional Expressions
Implement short-circuit logical expressions (&&, ||) and compact ternary operators in C for defensive null checks and inline branching.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.