#include <stdio.h>
int absolute(int n) {
if (n < 0) {
return -n;
}
return n;
}
This code defines a function that returns the absolute value of an integer. It checks if the number is negative, and if so, returns its negation; otherwise, it returns the number unchanged. The function works correctly for most integer values.
- Consider what happens when the input is the smallest possible negative integer, like -2147483648. In C, negating this value can cause an overflow because its positive counterpart is outside the range of int.
- Think about how integer overflow behaves in C and whether the function handles all possible inputs safely.