Type Casting & Type Conversion
Learn how to convert between data types in C. Master implicit (automatic) and explicit (manual) type casting, avoid integer division bugs, and understand when data loss occurs.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Understand implicit (automatic) type conversion
- ✓Use explicit casting with (type) syntax
- ✓Avoid the integer division pitfall
- ✓Know when data loss can occur
- ✓Convert between char and int (ASCII)
?Why Do We Need Type Casting?
Different data types use different amounts of memory and store values differently. Sometimes we need to convert between them:
Integer Division Problem
5 / 2 = 2 (not 2.5!) because both are integers.
Solution: Cast to float first!
Memory Optimization
Store a percentage (0-100) in a char (1 byte) instead of int (4 bytes).
75% memory savings!
Common scenarios: Mathematical calculations, function arguments, pointer conversions, reading binary data, interfacing with hardware.
01What is Type Casting?
Type casting (also called type conversion) is the process of converting a value from one data type to another. For example, converting an int to a float, or a char to an int.
Simple Example
int x = 10;
float y = x; // x (int) is converted to float
// y = 10.0
Implicit Casting
Done automatically by the compiler
Safe: smaller → larger type
Explicit Casting
Done manually by the programmer
May lose data: larger → smaller type
02Implicit Type Casting (Automatic)
The compiler automatically converts smaller types to larger types when needed. This is called type promotion and is always safe (no data loss).
Type Hierarchy (Promotion Order)
Smaller types are automatically promoted to larger types
1#include <stdio.h>23int main() {4 // Implicit conversions (automatic)5 6 char c = 'A'; // ASCII value 657 int i = c; // char → int (automatic)8 printf("char to int: %d\n", i); // 659 10 int x = 10;11 float f = x; // int → float (automatic)12 printf("int to float: %.1f\n", f); // 10.013 14 float pi = 3.14f;15 double d = pi; // float → double (automatic)16 printf("float to double: %lf\n", d); // 3.14000017 18 // In expressions, smaller types are promoted19 int a = 5;20 double b = 2.5;21 double result = a + b; // 'a' promoted to double22 printf("5 + 2.5 = %.1f\n", result); // 7.523 24 return 0;25}Implicit Casting Rules
- • char/short → int: Always safe (integer promotion)
- • int → float/double: Safe, but may lose precision for large ints
- • float → double: Always safe
- • In mixed expressions, smaller type is promoted to larger type
03Explicit Type Casting (Manual)
You can force a type conversion using the cast operator: (type). This is necessary when converting from a larger type to a smaller type, or when you want to control the conversion.
Syntax
(target_type) expression
// Examples:
(int) 3.14 // → 3
(float) 5 // → 5.0
(char) 65 // → 'A'
1#include <stdio.h>23int main() {4 // Explicit casting (manual)5 6 // float to int (truncates decimal part)7 float price = 19.99f;8 int whole = (int)price;9 printf("%.2f as int: %d\n", price, whole); // 1910 11 // double to int12 double pi = 3.14159;13 int truncated = (int)pi;14 printf("%.5f as int: %d\n", pi, truncated); // 315 16 // int to char (ASCII)17 int ascii = 72;18 char letter = (char)ascii;19 printf("%d as char: %c\n", ascii, letter); // H20 21 // Negative float to int22 float negative = -7.8f;23 int neg_int = (int)negative;24 printf("%.1f as int: %d\n", negative, neg_int); // -725 26 return 0;27}Data Loss Warning
When casting from larger to smaller types, you may lose data:
- •
float → int: Decimal part is truncated (not rounded) - •
int → char: Only lowest 8 bits kept - •
long → int: May overflow
04The Integer Division Problem
This is the #1 beginner mistake in C! When you divide two integers, the result is an integer (decimal part is lost), even if you store it in a float.
Wrong (Integer Division)
int a = 5, b = 2;
float result = a / b;
// result = 2.0 (NOT 2.5!)
5 ÷ 2 = 2 (integer), then stored as 2.0
✓Correct (Cast First)
int a = 5, b = 2;
float result = (float)a / b;
// result = 2.5 ✓
Cast a to float first, then divide
1#include <stdio.h>23int main() {4 int a = 5, b = 2;5 6 // WRONG: Integer division (loses decimal)7 float wrong = a / b;8 printf("Wrong: 5/2 = %.2f\n", wrong); // 2.009 10 // CORRECT: Cast at least one operand to float11 float right1 = (float)a / b;12 printf("Right1: (float)5/2 = %.2f\n", right1); // 2.5013 14 float right2 = a / (float)b;15 printf("Right2: 5/(float)2 = %.2f\n", right2); // 2.5016 17 float right3 = (float)a / (float)b;18 printf("Right3: (float)5/(float)2 = %.2f\n", right3); // 2.5019 20 // Using 1.0 also works (makes it a double)21 double right4 = 1.0 * a / b;22 printf("Right4: 1.0*5/2 = %.2f\n", right4); // 2.5023 24 // PRACTICAL EXAMPLE: Calculate average25 int sum = 17;26 int count = 5;27 28 float avg_wrong = sum / count; // 3.00 (wrong!)29 float avg_right = (float)sum / count; // 3.40 (correct!)30 31 printf("\nAverage of 17/5:\n");32 printf(" Wrong: %.2f\n", avg_wrong);33 printf(" Right: %.2f\n", avg_right);34 35 return 0;36}Remember This Rule!
int / int = int — To get a decimal result, cast at least one operand to float or double before dividing.
05Casting with Pointers
You can cast between pointer types. This is commonly used with void* pointers (generic pointers that can point to any type).
1#include <stdio.h>2#include <stdlib.h>34int main() {5 // void* is a generic pointer6 // malloc returns void*, must cast to specific type7 int *arr = (int*)malloc(5 * sizeof(int));8 9 if (arr == NULL) {10 printf("Memory allocation failed!\n");11 return 1;12 }13 14 // Use the array15 for (int i = 0; i < 5; i++) {16 arr[i] = (i + 1) * 10;17 }18 19 printf("Array: ");20 for (int i = 0; i < 5; i++) {21 printf("%d ", arr[i]);22 }23 printf("\n");24 25 free(arr);26 27 // Casting between pointer types (advanced)28 int num = 0x41424344; // "DCBA" in ASCII (little endian)29 char *ptr = (char*)#30 31 printf("\nBytes of 0x41424344: ");32 for (int i = 0; i < 4; i++) {33 printf("%c ", ptr[i]);34 }35 printf("\n");36 37 return 0;38}Modern C Note
In C (not C++), casting malloc() is optional becausevoid* implicitly converts to any pointer type. However, many programmers still cast for clarity and C++ compatibility.
06Character and Integer Conversion
In C, char is actually a small integer type. Every character has an ASCII code (number), so you can convert between them easily.
1#include <stdio.h>23int main() {4 // Character to integer (ASCII value)5 char letter = 'A';6 int ascii = (int)letter;7 printf("'%c' = %d (ASCII)\n", letter, ascii); // 'A' = 658 9 // Integer to character10 int code = 97;11 char ch = (char)code;12 printf("%d = '%c'\n", code, ch); // 97 = 'a'13 14 // Useful trick: convert digit char to number15 char digit = '7';16 int num = digit - '0'; // '7' - '0' = 55 - 48 = 717 printf("'%c' as number: %d\n", digit, num);18 19 // Convert number to digit char20 int value = 3;21 char digit_char = value + '0'; // 3 + 48 = 51 = '3'22 printf("%d as char: '%c'\n", value, digit_char);23 24 // Case conversion using ASCII math25 char lower = 'a';26 char upper = lower - 32; // 'a' (97) - 32 = 'A' (65)27 printf("'%c' to uppercase: '%c'\n", lower, upper);28 29 // Or use the difference between 'a' and 'A'30 char ch2 = 'b';31 char upper2 = ch2 - ('a' - 'A'); // Same as ch2 - 3232 printf("'%c' to uppercase: '%c'\n", ch2, upper2);33 34 // Print ASCII table (partial)35 printf("\nASCII table (65-90):\n");36 for (int i = 65; i <= 90; i++) {37 printf("%d=%c ", i, (char)i);38 if ((i - 64) % 9 == 0) printf("\n");39 }40 printf("\n");41 42 return 0;43}!Code Pitfalls: Common Mistakes & What to Watch For
These are the most common mistakes that trip up beginners. Study them carefully to avoid hours of debugging!
Mistake 1: Integer Division
float avg = 10 / 3; // = 3.0, not 3.33!
✓ Fix: float avg = 10.0 / 3; or (float)10 / 3
Mistake 2: Casting After Operation
float result = (float)(5 / 2); // = 2.0, not 2.5!
✓ Fix: float result = (float)5 / 2; — Cast before dividing
Mistake 3: Overflow When Casting
int big = 300;
char small = (char)big; // = 44 (overflow!)
✓ Fix: Check value is in range before casting (char: -128 to 127)
Mistake 4: Precision Loss
int big = 123456789;
float f = big; // May lose precision!
✓ Fix: Use double for large integers (more precision)
09Frequently Asked Questions
Q:Why does 5/2 give 2 instead of 2.5?
A: In C, int / int = int. Integer division truncates (drops) the decimal part. To get 2.5, cast one operand:(float)5 / 2 or 5.0 / 2. This is the #1 casting gotcha for beginners!
Q:What's the difference between implicit and explicit casting?
A: Implicit: Compiler does it automatically for safe conversions (int to float). Explicit: You force it with (type) syntax. Explicit is needed for: lossy conversions (float to int), pointer casts, or overriding default behavior.
Q:Is it safe to cast pointers?
A: Pointer casts are powerful but dangerous. Casting void* to a typed pointer is common and safe. Casting between unrelated types (like int* tofloat*) can cause undefined behavior due to alignment and aliasing rules. Only cast pointers when you understand the memory layout.
Q:What happens when I cast a float to an int?
A: It truncates (cuts off) the decimal part — doesn't round! (int)3.9 = 3,(int)-3.9 = -3. For rounding, useround(), floor(), or ceil() from <math.h>.
Q:What is type promotion?
A: When different types are mixed in an expression, the "smaller" type is promoted to the "larger" one. Hierarchy:char → int → float → double. Sochar + int becomes int,int + float becomes float.
09Summary
✓Implicit (Automatic)
- • Compiler does it automatically
- • Safe: smaller → larger type
- • char → int → float → double
- • Happens in mixed expressions
Explicit (Manual)
- • Use
(type)syntax - • May lose data: larger → smaller
- • Required for pointer casting
- • Use to prevent integer division
Key Takeaway
Always remember: int / int = int. Cast to float before dividing to get decimal results!
Test Your Knowledge
Related Tutorials
C Operators and Expressions
Learn all the operators in C: math (+, -, *, /), comparisons (==, <, >), and logical operations (&&, ||). Build expressions that compute values.
Data Types & Variables
Learn to store different kinds of data: numbers (int), decimals (float), and characters (char). Understand how much memory each type uses.
Operator Precedence & Associativity
Understand which operators are evaluated first. Learn the PUMAS REBL TAC memory trick and when to use parentheses.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!