The ‘C’ test. Part – XII

Code examples

12. What does the following code output and why?

void foo(void)
{
           unsigned int a = 6;
           int b = -20;
          (a+b > 6) ? puts(“> 6”) : puts(“<= 6”);

}

This question tests whether you understand the integer promotion rules in C-an area that I find is very poorly understood by many developers.

Anyway, the answer is that this outputs “> 6.” The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus -20 becomes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently (see Reference 2).

If you get this one wrong, you are perilously close to not getting the job.

…to be continued

Leave a comment