The following code defines a simple absolute value macro. It fails in at least one case. What value does it fail on? Think about what happens at the boundary. If you cannot find the issue, you can test some values quickly in code.
#define abs(n) ((n) < 0 ? -(n) : (n) )
Let's say, we need to check the value of abs(++n), where n is -5. The result should be 4 as -5+1 is -4 and the absolute value of -4 is 4.
But we get the result as 3. Below is the code snippet:
Reason:
The above macro when called expands to, m = (((++n) < 0) ? -(++n) : (++n));. This leads to n to be incremented twice rather than once.
The solution for this case would be increment the n first and then calculate abs value or we can use inline functions.
Get Answers For Free
Most questions answered within 1 hours.