C in 100 Seconds: Type Casting | Episode 15
Video: C in 100 Seconds: Type Casting — Why 7/2 Is 3 and How to Fix It | Episode 15 by Taught by Celeste AI - AI Coding Coach
Watch full page →Type Casting — Converting Between Types in C
C in 100 Seconds, Episode 15
C lets you convert values from one type to another. Sometimes the compiler does it automatically. Sometimes you do it by hand. Either way, you should know what's happening to your data.
Explicit Casting
When you divide two integers, you get integer division. Cast one to float to get the real answer:
int a = 7, b = 2;
printf("int / int = %d\n", a / b); // 3
printf("cast to float = %.2f\n", (float)a / b); // 3.50
The (float) before a tells the compiler to treat a as a float for this operation. Now C performs floating-point division.
Truncation
Casting a double to an int chops off the decimal part:
double pi = 3.14159;
int truncated = (int)pi;
printf("pi = %f\n", pi); // 3.141590
printf("truncated = %d\n", truncated); // 3
No rounding — the fractional part is simply discarded.
Implicit Casting
C automatically converts char to int in many contexts:
char ch = 'A';
printf("char %c = int %d\n", ch, ch); // char A = int 65
Every char has an underlying integer value from the ASCII table. 'A' is 65, 'B' is 66, and so on. This implicit conversion happens constantly behind the scenes.
Why Does This Matter?
Type casting is where data loss happens in C. A double → int cast silently throws away precision. An int → char cast can overflow. C won't warn you at runtime — you're expected to know when a cast is safe and when it's destructive.
Full Code
#include <stdio.h>
int main() {
int a = 7, b = 2;
printf("int / int = %d\n", a / b);
printf("cast to float = %.2f\n", (float)a / b);
double pi = 3.14159;
int truncated = (int)pi;
printf("pi = %f\n", pi);
printf("truncated = %d\n", truncated);
char ch = 'A';
printf("char %c = int %d\n", ch, ch);
return 0;
}
Compile and Run
gcc casting.c -o casting
./casting
Next episode: Header Files — splitting your code across multiple files.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode15