If C has to compile the following code
int a = 5, b = 3, c = 7;
a = b---c;
Would it have to parse it as a = b-- - c
, a = b - --c
, or is it undefined behavior?
If C has to compile the following code
int a = 5, b = 3, c = 7;
a = b---c;
Would it have to parse it as a = b-- - c
, a = b - --c
, or is it undefined behavior?
The compiler considers the longest sequence of characters to determine a token.
So this statement
a = b---c;
is equivalent to
a = b-- - c;
That is in the expression of the right side of the assignment there is the postfix decrement operator --
followed by the additive operator -
.
From 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. ...
Thus as result the values of the variables after executing this statement will be
a = -4, b = 2, c = 7
Also pay attention to that a valid sub-expression may be enclosed in parentheses. You may write for example
a = ( b-- )-c;
but you may not write
a = ( b- )--c;
On the other hand, you may also write
a = b-( --c );
In this case the values of the variables after executing the statement will be
a = -3, b = 3, c = 6
It is parsed as : a = b-- - c, and b-- means post-decrement, i.e. decrement after taking the value of b to compute b - c
run this code and watch the output :
#include <stdio.h>
int main()
{
int a = 5, b = 3, c = 7;
a = b---c;
printf ("a is : %d\n", a);
printf ("b is : %d\n", b);
printf ("c is : %d\n", c);
}
output :
a is : -4
b is : 2
c is : 7