Search code examples
ccompilationoperator-keywordoperator-precedence

A question about precedence and associativity in C


I had a question about something I'm failing to understand.

Since white space removal is part of C compiling process, then how does a C compiler differentiates between the following:

Case1:

int x = 2,y=4;
int z = x+++y;
printf("%d", z);//gives 6

Case 2:

 int x = 2,y=4;
 int z = x+ ++y;
 printf("%d", z);//gives 7

Notice the space I added after x+, making the ++ stick to the y rather than the x, but how does this happen if white spaces are removed?


Solution

  • C has a greedy left-to-right lexer:

    http://port70.net/~nsz/c/c11/n1570.html#6.4p4:

    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.

    ...

    so +++ must be recognized as ++ + and never as + ++.

    Precedences and associativities then determine how the ++ or the + token bind (http://port70.net/~nsz/c/c11/n1570.html#A.2.1).

    Simply put, postfix operators bind tighter than prefix operators, which bind tighter than binary operators. So x++ + y means (x++) + (y) and never (x) (++(+(x)) (which would be nonsensical for other reasons) (and e.g., &x->member means &(x->member) and not (&x)->member), but the confusion here only seems to be in how the fragment is tokenized.