basics · beginner · ~15 min
Practise simple branching while handling boundary values.
Implement int my_abs(int n) returning the absolute value of n. Watch out for INT_MIN.
Absolute value is one of the simplest functions you'll write, but it has a famous trap: -INT_MIN doesn't fit in int. Handling that gracefully separates careful programmers from sloppy ones.
int my_abs(int n) { /* TODO */ return 0; }
Returning -n without the < 0 check (the negation has no effect for positive n). Using fabs() (that's for doubles).
0 → 0. INT_MIN — its magnitude exceeds INT_MAX. Skip or widen.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.