C Type Conversion
In this page:
Implicit Conversion
When an expression mixes types, C promotes the narrower operand to the wider one before evaluating -- an int added to a double is converted to double first, so the result keeps the fractional part instead of being silently truncated.
Example: Implicit Conversion
#include <stdio.h>
int main() {
int a = 5;
double b = 2.0;
printf("%.1f", a + b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Explicit Casts
Writing (int), (float), or (char) in front of a value forces a conversion the compiler wouldn't do on its own, useful when you need integer division to instead produce a fractional result or want to strip a value down to its integer part on purpose.
Example: Explicit Casts
#include <stdio.h>
int main() {
int a = 7, b = 2;
double result = (double)a / b;
printf("%.1f", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Truncation and Data Loss
Casting a float to an int doesn't round -- it discards everything after the decimal point, so (int)9.9 becomes 9, not 10; casting a large value into a smaller type can also silently wrap around instead of raising any error.
Example: Truncation and Data Loss
#include <stdio.h>
int main() {
float f = 9.9f;
int truncated = (int)f;
printf("%d", truncated);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Signed and Unsigned Conversion
Assigning a negative signed value to an unsigned variable doesn't fail -- it wraps around using modular arithmetic, so -1 stored in an unsigned int becomes the type's maximum representable value, a frequent source of subtle bugs in loop counters.
Example: Signed and Unsigned Conversion
#include <stdio.h>
int main() {
int negative = -1;
unsigned int wrapped = negative;
printf("%u", wrapped);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Casting Compared to C++
Plain C only has this one C-style cast syntax, (type)value, applied uniformly to every kind of conversion; C++ later split this into four distinct operators -- static_cast, dynamic_cast, const_cast, and reinterpret_cast -- specifically to make each conversion's intent and safety explicit.
Example: Casting Compared to C++
#include <stdio.h>
int main() {
double d = 9.5;
int i = (int)d;
printf("%d", i);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers