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 ...">

"a ++ + i" equals "(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 looks like 4 4 5 . But why is a+++i equal 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 priority ?

And will it work on all compilers?

+6
source share
2 answers

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

If the input stream is parsed in the preprocessing token to the specified character, the next preprocessing token is the longest sequence of characters that can make up the preprocessing token.

There is also an example here:

the program fragment x+++++y parsed as x ++ ++ + y , which violates the restriction on increments, although parsing x ++ + ++ y can give the correct expression.

+5
source

I can’t say everything, since the implementation of the C compiler may be different. But overall, yes, you're right. Compiler C must be greedy, i.e. Read as much as possible, therefore +++ == ++ + .

+1
source

Source: https://habr.com/ru/post/976355/


All Articles