I tested this on different machine and on different compiler, but I gave out the same output:
int sum = 10, i = 5;
printf("%d", sum+++i);
Is this well-defined or undefined behavior in C?
I tested this on different machine and on different compiler, but I gave out the same output:
int sum = 10, i = 5;
printf("%d", sum+++i);
Is this well-defined or undefined behavior in C?
It's well defined. sum+++i
is parsed as sum++ + i
, which results as 15
(with the side effect of incrementing sum
).
C11 §6.4 Lexical elements
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 one exception to this rule: header name preprocessing tokens are recognized only within
#include
preprocessing directives and in implementation-defined locations within#pragma
directives. In such contexts, a sequence of characters that could be either a header name or a string literal is recognized as the former.
And a similar example is followed:
EXAMPLE 2 The program fragment
x+++++y
is parsed asx ++ ++ + y
, which violates a constraint on increment operators, even though the parsex ++ + ++ y
might yield a correct expression.
This statement
printf("%d", sum+++i);
corresponds to
printf("%d", sum++ + i);
and is a well-formed statement. There is no any undefined behaviour.
The output will be
15
According to the C Standard (6.4 Lexical elements)
4 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.