← Back to C Course | Chapter 12: Advanced Topics | Lesson 2 of 20

C Type Casting

What is Type Casting?

Type casting converts a value from one data type to another so an expression evaluates with the precision or range you actually intend, rather than whatever the compiler would pick by default. It matters most whenever mixed types meet in the same expression, such as combining an int with a double.

Example: What is Type Casting?

c
#include <stdio.h>
int main() {
	int a = 5;
	double b = (double)a;
	printf("%.1f", b);
	return 0;
}

Implicit Type Conversion

Implicit conversion happens automatically whenever the compiler needs to reconcile mismatched operand types in an expression, silently promoting the narrower type (like char or int) to the wider one (like double) so no precision is lost during the calculation. This is convenient, but it can hide bugs if you don't expect the promotion.

Example: Implicit Type Conversion

c
#include <stdio.h>
int main() {
	int a = 5;
	double b = 2.5;
	printf("%.1f", a + b);
	return 0;
}

Explicit Type Casting

Explicit casting means writing the target type in parentheses directly before the value, such as (double)x, to force a conversion the compiler wouldn't otherwise perform on its own. Reach for it whenever you need to override C's default promotion rules deliberately, not just to silence a compiler warning.

Example: Explicit Type Casting

c
#include <stdio.h>
int main() {
	double x = 9.7;
	printf("%d", (int)x);
	return 0;
}

Preventing Integer Division Loss

Because integer division in C truncates toward zero and drops any remainder, dividing two int variables like 7/2 always yields 3, not 3.5. Casting at least one operand to float or double before the division forces C to use floating-point arithmetic and keep the fractional part.

Example: Preventing Integer Division Loss

c
#include <stdio.h>
int main() {
	int a = 7, b = 2;
	printf("%.1f", (float)a / b);
	return 0;
}

Float to Integer Truncation

Converting a float or double to an int truncates the value toward zero rather than rounding it, so 9.99 becomes 9 and -9.99 becomes -9, not -10. If you actually want rounding, call round() from math.h before casting, since the cast alone will always chop off the decimal part.

Example: Float to Integer Truncation

c
#include <stdio.h>
int main() {
	printf("%d %d", (int)9.99, (int)-9.99);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.