Search code examples
cassignment-operatorcompound-assignment

What is the difference between += and =+ C assignment operators


I was wondering if there was a difference between =+ and += (and other assignment operators too). I tried and both did the same thing. So is there a difference or is there a convention? Do both work because my compilers dont check for standarts?

Edit: I made a mistake. I used bad inputs during my testing which led me to thinking they are both doing the same thing. Turns out they are two different things.

+= adds rvalue to lvalue

x += y;
x = x + y;

=+ assigns rvalue to lvalue

x =+ y;
x = +y;
x = y;

Solution

  • In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and +. Punctuation tokens are allowed to be adjacent.

    So if you write:

    x += y;
    

    it's equivalent to

    x = x + y;
    

    except that x is only evaluated once (which can matter if it's a more complicated expression).

    If you write:

    x =+ y;
    

    then it's parsed as

    x = + y;
    

    and the + is a unary plus operator.

    Very early versions of C (around the mid 1970s, before the publication of K&R1 in 1978) used different symbols for compound assignments. Where modern C uses +=, early C used =+. Early C had no unary + operator, but it did have a unary - operator, and the use of =- caused problems; programmers would write x=-y intending it to mean x = -y, but it was silently interpreted as x =- y. The language was changed some time between 1975 and 1978 to avoid that problem. As late as 1999, I worked with a compiler (VAXC on VMS) that would warn about an ambiguous use of =-, but would use the older meaning. That shouldn't be a concern now unless you're a hobbyist playing with some very old software and/or hardware.

    (A 1975 C Reference Manual shows the old =-, =+, et al forms of the compound assignment operators. The first edition of The C Programming Language by Kernighan and Ritchie, published in 1978, shows the modern -=, +=, et al, but mentions the older forms under "Anachronisms".)