C safely taking absolute value of integer
<p>Consider following program (C99):</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;inttypes.h&gt;

int main(void)
{
    printf("Enter int in range %jd .. %jd:\n &gt; ", INTMAX_MIN, INTMAX_MAX);
    intmax_t i;
    if (scanf("%jd", &amp;i) == 1)
        printf("Result: |%jd| = %jd\n", i, imaxabs(i));
}
</code></pre>

<p>Now as I understand it, this contains easily triggerable <em>undefined behaviour</em>, like this:</p>

<pre><code>Enter int in range -9223372036854775808 .. 9223372036854775807:
 &gt; -9223372036854775808
Result: |-9223372036854775808| = -9223372036854775808
</code></pre>

<p>Questions:</p>

<ol>
<li><p>Is this really undefined behaviour, as in "code is allowed to trigger any code path, which any code that stroke compiler's fancy", when user enters the bad number? Or is it some other flavor of not-completely-defined?</p></li>
<li><p>How would a pedantic programmer go about guarding against this, <em>without</em> making any assumptions not guaranteed by standard?</p></li>
</ol>

<p>(There are a few related questions, but I didn't find one which answers question 2 above, so if you suggest duplicate, please make sure it answers that.)</p>