user54750: 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? 

user13432: abs() is defined in Arduino.h as a macro:
 #define abs(x) ((x)>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)>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!

54750: <p>When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.</p>

<pre><code>int sensor = 0;
sensor = abs(analogRead(A0) - 512);
</code></pre>

<p>Values:</p>

<pre><code>77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31
</code></pre>

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

<pre><code>int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);
</code></pre>

<p>I don't think this is an integer overflow as in this <a href="https://arduino.stackexchange.com/questions/25989/getting-negative-results-from-calculations">post</a> because when I switch to <code>long sensor = 0</code> I get the same negative results.</p>

<p>What's going on here? </p>
 13432: <p><code>abs()</code> is defined in <a href="https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h#L94" rel="nofollow noreferrer">Arduino.h</a> as a macro:</p>

<pre><code> #define abs(x) ((x)&gt;0?(x):-(x))
</code></pre>

<p>A macro does not evaluate in the same way as a function. </p>

<pre><code> sensor = abs(analogRead(A0) - 512);
</code></pre>

<p>This statement will be expanded at compile-time to:</p>

<pre><code> sensor = ((analogRead(A0) - 512)&gt;0?(analogRead(A0) - 512):-(analogRead(A0) - 512));
</code></pre>

<p>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:</p>

<pre><code>#undef abs
</code></pre>

<p>This will remove the macro <code>abs()</code> and the <a href="http://www.cplusplus.com/reference/cstdlib/abs/" rel="nofollow noreferrer">standard library function</a> will be used instead. </p>

<p>Cheers!</p>
