← Back to C Course | Chapter 1: Introduction & Basics | Lesson 15 of 21

C Type Conversion

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

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

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

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

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

c
#include <stdio.h>
int main() {
	float f = 9.9f;
	int truncated = (int)f;
	printf("%d", truncated);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int negative = -1;
	unsigned int wrapped = negative;
	printf("%u", wrapped);
	return 0;
}

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++

c
#include <stdio.h>
int main() {
	double d = 9.5;
	int i = (int)d;
	printf("%d", i);
	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.