Today I noticed that the weird b + + c;
expression is considered valid in C. I am wondering if there is a reason behind it; especially, given that b ++ c;
and b + ;
are considered syntax errors.
I do not know where to look for some information, I thought StackOverflow might be a good place to ask for some insight (I am using gcc
for compilation).
I found this expression in an old code of mine, probably an error caused due to removing a variable from the middle of the summation and forgetting to also remove the operator sign.
#include <stdio.h>
int main()
{
int a = 100;
int b = 200;
int c = 300;
a = b + + c; /* <-- why this is not a syntax error ? */
printf("a = %d\n", a); /* <-- prints a = 500 */
return 0;
}
b + + c
is equivalent to b + (+c)
where the second + is an unary plus operation that actually does nothing here.
(a bit similar to -c
for unary negation but with no real effect).
This is because of the operator precedence: unary +
-
has higher precedence than binary +
-
.
As @RobertHarvey commented you should not actually write code like this as there's no reason to over-complicate a simple a = b + c;
.