开发者

C Programming: += vs =+

My professor and I are engaging in a bit of a debate about the +=开发者_JAVA技巧 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 +=?


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.


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).


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.


+ is also a unary operator as is -.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜