Type Conversion & Casting in C
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.
Usual promotions first
Small integers promote to int, then mixed expressions convert toward double — the compiler climbs a fixed rank ladder automatically.
Cast to force floating math
(double)votes / total divides as doubles — the cast applies before /, rescuing averages from truncation.
Narrowing drops silently
int x = 3.99; stores 3 with at most a warning — the fractional part vanishes without ceremony.
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.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.