Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: += vs =+

Tags:

c

operators

My professor and I are engaging in a bit of a debate about the += operator in C. He says that += or =+ will work, but he is not certain why =+ works.

int main()
{
    int i = 0, myArray[5] = {1,1,1,1,1};

    while(i < 5)
    {
            myArray[i] += 3 + i;
            printf("%d\n", myArray[i]);
            i++;
    }

    system("pause");
}

The output will yield 4, 5, 6, 7, 8. Changing the += operator to =+ yields the same results. However -= does not do the same as =- (which is obvious as it treats the 3 as a 3).

So C gurus:

  • Why does this work with =+?
  • How does a C compiler treat =+ versus +=?
like image 858
A Student Avatar asked Feb 16 '11 02:02

A Student


3 Answers

He is wrong; += is completely different from =+.

The expression x =+ 3 is parsed as x = (+3).
Here, + becomes the (rather useless) unary + operator. (the opposite of negation)

The expression x =- 3 is parsed as x = (-3), using the unary negation operator.

like image 73
SLaks Avatar answered Oct 25 '22 03:10

SLaks


Your professor is remembering ancient versions of C in which =+, =-, =* etc did in fact mean the same thing as +=, -=, *= etc. (We're talking older than the version generally referred to as "K&R" here. Version 6 UNIX, if memory serves.)

In current versions of C, they do not mean the same thing; the versions with the equals sign first will be parsed as if there was a space in between the equals and whatever comes after. This happens to produce a valid program (albeit not a program that does what you expect) for =- and =+ because - and + can be used as unary operators.

=* or =/ could be used to settle the argument. a *= 3 will multiply a by three, and a /= 3 will divide it by three, but a =* 3 is a semantic error (because unary * can only be applied to pointers) and a =/ 3 is a syntax error (because / can not be used as an unary operator).

like image 29
zwol Avatar answered Oct 25 '22 04:10

zwol


Code

myArray[i] += 3 + i;

will yield myArray[i] = myArray[i] + 3 + i;

whereas

myArray[i] =+ 3 + i;

yields myArray[i] = 3 + i

that's what I got.

like image 40
ardiyu07 Avatar answered Oct 25 '22 03:10

ardiyu07