C Programming: + = vs = +

My professor and I participate in discussions regarding the + = operator in C. He says that + = or = + will work, but he is not sure 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 give 4, 5, 6, 7, 8. Changing the operator + = to = + gives the same results. However - = does not do the same thing as = - (which is obvious since it treats 3 as 3).

So the guru:

  • Why does this work with = +?
  • How does the C compiler consider = + versus + =?
+8
c operators
source share
4 answers

He is not right; += completely different from =+ .

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

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

+22
source share

Your professor remembers ancient versions of C in which =+ , =- , =* , etc. actually meant the same thing as += , -= , *= , etc. (We're speaking higher than the version commonly referred to here as “K & R.” UNIX version 6, if memory serves.)

In current versions of C, they do not mean the same thing; versions with an equal sign will first be sorted out, as if there was a space between equals and what comes after. This means that for =- and =+ there is a valid program (although not a program that does what you expect), because - and + can be used as unary operators.

=* or =/ can be used to resolve the argument. a *= 3 multiplies a by three, and a /= 3 divides it into three, but a =* 3 is a semantic error (since unary * can only be applied to pointers), and a =/ 3 is a syntax error (since / does not can be used as a unary operator).

+14
source share

the code

 myArray[i] += 3 + i; 

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

then

 myArray[i] =+ 3 + i; 

gives myArray[i] = 3 + i

what i got.

+3
source share

+ also a unary operator as is - .

+1
source share

All Articles