Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sum+++i undefined behavior in C? [duplicate]

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?

like image 525
Kevin Dong Avatar asked Dec 04 '25 13:12

Kevin Dong


1 Answers

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 as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.

like image 99
Yu Hao Avatar answered Dec 07 '25 16:12

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!