5

I have a question on a program that includes the following if statement:

if (x =+ 4){
    x += 5;
}

I've never seen anything like that before, surely it isn't a typo? Does =+ actually do anything?

Hoyeh
  • 59
  • 1
  • 3

4 Answers4

20
x =+ 4

means

x= (+4)

or simply

x=4

though such construction syntactically correct and can be compiled, does not make much sense and most probably a typo, where x==4 was intended, especially that it is used as condition for if

Slava
  • 43,454
  • 1
  • 47
  • 90
2

In the early days of C, =+ was the same as +=, but that's long gone and never made its way into C++.


=+a is understood to be = (+a)

The unary + operator promotes the argument to an int if it's of a narrower type, otherwise it's a no-op.

And = is regular assignment.


You can contrive a difference between =+ and = in this way:

If = was twice overloaded for two particular pairings, for example {Foo, int} and {Foo, char}, and you had an instance of Foo foo and a char c, then

foo = c // calls the overload taking a `char`

and

foo =+ c // calls the overload taking an `int`

would call different overloads.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Sorry, my initial answer was due to foolishly misreading the question.

The correct answer, is this code simply assigns x the value of positive 4, because this is then non zero it satisfies the if and increments it further by 5.

A simpler form of this program in its current state would be:

x = 9;

However I strongly suspect there was a typo involved and the statement inside the if condition should either be x == 4, x += 4 or x != 4 depending on context.

Vality
  • 6,577
  • 3
  • 27
  • 48
0

OK just to round this out, I did find that my hunch was right, =+ and =- are indeed just obsolete forms of the += and -= op's in use today:

Stack Overflow: What does =+ mean in C? https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_064.HTM (now that's a vintage web page!)

and specifically

https://en.wikipedia.org/wiki/C_(programming_language)#K.26R_C

tells us that they were changed: "Compound assignment operators of the form =op (such as =-) were changed to the form op= (that is, -=) to remove the semantic ambiguity created by constructs such as i=-10, which had been interpreted as i =- 10 (decrement i by 10) instead of the possibly intended i = -10 (let i be -10)."

So it's not to do with making an argument explicitly +ve or -ve. You can simply substitute the modern forms, eg use += in place of =+.

Community
  • 1
  • 1
BernardW
  • 1
  • 3
  • You could delete your other, now obsolete answers in favor of this one. Also note that you are referencing C, but this question is about C++. – eis Oct 15 '17 at 08:06
  • I''ve deleted your previous 'answers', this isn't a forum, you can *[edit]* your answers to improve them. – Martijn Pieters Oct 16 '17 at 10:25