Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C plus operator semantics

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 Stack Overflow 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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 nagation 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;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading