Learn C
#include "variablesdatatypes/type_conversion.h"

Type Conversion & Casting in C

#concept

C converts implicitly (int to double in mixed arithmetic, followingUsual arithmetic conversions) and explicitly through casts: (double)votes / total forces floating-point division. Casts override the type system by fiat — powerful and unchecked, so each one should be deliberate.

Narrowing (double into int, int into char) drops data silently, and integer division truncates — the two great silent-data-loss bugs. Pointer casts (int* to char*) reinterpret raw bytes, which is legitimate systems work but strict-aliasing-sensitive: punning through unions or memcpy is safer than wild pointer casts.

#how it works
1

Usual promotions first

Small integers promote to int, then mixed expressions convert toward double — the compiler climbs a fixed rank ladder automatically.

2

Cast to force floating math

(double)votes / total divides as doubles — the cast applies before /, rescuing averages from truncation.

3

Narrowing drops silently

int x = 3.99; stores 3 with at most a warning — the fractional part vanishes without ceremony.

4

Pointer casts reinterpret bytes

Casting between pointer types re-reads the same memory as a new type — valid systems technique, undefined behavior when aliasing rules break.

#example
#include <stdio.h>
 
int main(void) {
int votes = 7, total = 2;
double ratio = (double)votes / total;
int chopped = (int)3.99;
printf("%.1f, %d\n", ratio, chopped);
return 0;
}
Output
3.5, 3
1Without the cast, 7 / 2 would truncate to 3; casting votes first promotes the whole division to double.
2(int)3.99 truncates toward zero to 3 — deliberate, visible data loss.
3%.1f prints one decimal (3.5) and %d prints the int — specifiers matched to converted types.
#use cases
Fixing integer-division averages with one cast on the numerator
Reading sensor bytes through reinterpreted pointer types in drivers
Auditing narrowing conversions -Wconversion flags in safety-critical code
Preferring memcpy/union punning over wild pointer casts for type punning

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.