Unexpected negative values from abs() function inline with analogRead When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.

int sensor = 0;
sensor = abs(analogRead(A0) - 512);


Values:

77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31


When running the (apparently) mathematically equivalent code below I get exclusively positive values. 

int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);


I don't think this is an integer overflow as in this post because when I switch to long sensor = 0 I get the same negative results.

What's going on here?
abs() is defined in Arduino.h as a macro:

 #define abs(x) ((x)&gt;0?(x):-(x))


A macro does not evaluate in the same way as a function. 

 sensor = abs(analogRead(A0) - 512);


This statement will be expanded at compile-time to:

 sensor = ((analogRead(A0) - 512)&gt;0?(analogRead(A0) - 512):-(analogRead(A0) - 512));


Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

#undef abs


This will remove the macro abs() and the standard library function will be used instead. 

Cheers!