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?
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?
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
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.
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.
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 =+.