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.

Advertisements

3 Responses to “Fun with C operators”

  1. Unary plus was actually added to the C Programming Language as part of ANSI standardisation “to match the unary minus”. I noticed that odd feature while flipping through the book on the train last week.

    • Yes, indeed this is covered in the C99 rationale document which says:

      “Unary plus was adopted by the C89 Committee from several implementations, for symmetry with unary minus.”

      and it is also mentioned in the Annotated C++ Reference Manual(ARM):

      “Unary plus is a historical accident and generally useless.”

      See this SO question for the details: http://stackoverflow.com/a/30791078/1708801

  2. This is explained by the maximal munch rule which is covered in the draft C99 standard §6.4 which says:

    “If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token”

    One of the classical cases explicitly covered in the same section is:

    x+++++y

    See this Stackoverflow question for all the details: http://stackoverflow.com/a/24947922/1708801

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: