Type Conversion in C
On this page (11sections)
Introduction
Type conversion (also called type casting) changes a value from one data type to another. C performs some conversions automatically; others require an explicit cast.
Implicit Conversion
When operands of different types appear in an expression, C promotes the smaller type to the larger:
int a = 5;
float b = 2.5f;
float result = a + b; /* int 5 promoted to float 5.0 */
In assignment, the right-hand value is converted to the left-hand type:
float f = 9; /* int 9 → float 9.0 */
int n = 3.14f; /* float truncated → int 3 */
Explicit Conversion (Casting)
Use (type) before a value to force conversion:
#include <stdio.h>
int main(void) {
float pi = 3.14159f;
int whole = (int)pi;
printf("pi as float: %.5f\n", pi);
printf("pi as int: %d\n", whole);
return 0;
}
Sample Output
pi as float: 3.14159
pi as int: 3
Integer Division vs Float Division
A common conversion pitfall:
#include <stdio.h>
int main(void) {
int a = 5, b = 2;
printf("int division: %d\n", a / b); /* 2 */
printf("float division: %.1f\n", (float)a / b); /* 2.5 */
return 0;
}
Sample Output
int division: 2
float division: 2.5
Cast before division to avoid truncating the result.
char and int Conversion
char is a small integer type. Characters and their ASCII codes convert freely:
char ch = 'A';
printf("char: %c, code: %d\n", ch, ch); /* A, 65 */
Best Practices
- Cast explicitly when the conversion affects correctness (especially division).
- Be aware of truncation when casting floating-point to integer.
- Use
(float)or3.14fto ensure floating-point arithmetic.
Common Mistakes
(int)(3.9)gives3, not4— no rounding.- Overflow when converting a large
longtointon systems where sizes differ. - Forgetting that
a / bwith two integers always produces an integer result.
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- C Introduction — Start here — what C is and why it matters.
- Command Line Arguments in C (argc and argv) — More in c basics.
- C History — More in c basics.
Frequently Asked Questions
What is the difference between implicit and explicit conversion?
Implicit conversion happens automatically (e.g. int to float in mixed arithmetic). Explicit conversion uses a cast: (type)value.
What happens when you cast float to int?
The fractional part is truncated (not rounded). (int)3.9 becomes 3, not 4.