Posts Tagged ‘grammar’

Articles

Fun with C operators

In C on December 13, 2010 by Matt Giuca Tagged:

Quick quiz: What does this C code print?

    int a, b;
    a = 1;
    b = 2;
    printf("%d\n", a+++ + +++b);
    printf("%d\n", a);
    printf("%d\n", b);

Answer:

   4
   2
   3

What the heck is a “+++” operator? It turns out the C grammar is quite liberal with its whitespace (intentionally), which can create some strange “ambiguities”. There are actually four operators in play here: x++ (post-increment), ++x (pre-increment), +x (unary plus) and x + y (addition). If you haven’t seen it, unary plus is analogous to –x (unary minus), only completely useless — unary minus inverts the sign of a number, while unary plus keeps it the same. So the expression “a+++ + +++b” is tokenised as “a ++ + + ++ + b” can be formatted better as:

    (a++) + (+(++(+b)))

(Note the colour coding: The “+” that looks like addition in the original is actually a unary plus.) So, this code reads: “Ensure b keeps its sign, pre-increment b, then ensure the result keeps its sign again, then add the result to a. Finally, post-increment a.” Hence its value is 1 + (2+1) = 4, and the values of both a and b are incremented.