Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "a+++i" equal to "(a++)+i"

#include <stdio.h>

int main(void) 
{
    int a = 1, i = 3, x, y, z;
    a = 1; i = 3;
    x = a+++i;
    a = 1; i = 3;
    y = a++ + i;
    a = 1; i = 3;
    z = a + ++i;
    printf("%d %d %d", x, y, z);
    scanf(" ");
    return 0;
}    

This code output appears to be 4 4 5. But why is a+++i equals to a++ + i?

Is it because compilers always read source code from left to right?

Or is it because the operation follows the order of precedence?

And will it work the same on all compilers?

like image 857
Santi Santichaivekin Avatar asked Oct 07 '14 12:10

Santi Santichaivekin


2 Answers

C11 standard, part 6.4 (Lexical elements)/4 says (and in C99 it's the same):

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.

There is also an example there:

The program fragment x+++++y is parsed as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.

like image 180
Anton Savin Avatar answered Sep 23 '22 21:09

Anton Savin


I can't say all, since C compiler implementation may be different. But generally yes, you are right. A C compiler is supposed to be greedy, i.e. read as much as possible, so +++ == ++ +.

like image 42
Vin Avatar answered Sep 21 '22 21:09

Vin