+= Operator in C++ - c++

Someone please tell me the difference between the following codes which add two variables of datatype int. I want to know which one is better.
Code A:
sum = sum + value;
Code B:
sum += value;
We usually prefer ++ operator over += 1. Is there any specific reason behind that as well ?
I want to know the difference between the above codes with respect to the conventions or efficiency level. Which one is recommended ?

While the end result of the e.g. someVar++ operator is the same as someVar += 1 there are other things playing in as well.
Lets take a simple statement like
foo = bar++;
It's actually equivalent (but not equal) to
temp = bar;
bar += 1;
foo = temp;
As for the prefix and suffix increment or decrement operators, they have different operator precedence, which will affect things like pointer arithmetic using those operators.
As for the difference between
foo += 1;
and
foo = foo + 1;
there's no different for primitive types (like int or float) or pointer types, but there's a very big difference if foo is an object with operator overloading. Then
foo += 1;
is equal to
foo.operator+=(1);
while
foo = foo + 1;
is equal to
temp = foo.operator+(1);
foo.operator=(temp);
Semantically a very big difference. Practically too, especially if any of the operator overload functions have side-effects, or if the copy-constructor or destructor have some side-effects (or you forget the rules of three, five or zero).

One calls operators = and + the later calls operator +=.
operators ++ and += are preferred because of readability - most programmers know what they mean.
On the other hand most modern compilers will generate the same code for += 1 as ++ and +/= as += for builtin types;
But for user defined classs, the actual operators will be called and it's up to the implementer of those classs to make sense of it all. In these cases ++ and += can be optimal.

cout << sum++; Would print out the value of sum before it was incremented. Also, depending on what you are doing, you can overwrite the operators += and +.

When you minimize code, you reduce the chance of an error (a typographical error or a logical error).
By using
sum += value;
you reduce the chance - ever so slightly - of an error while typing
sum = sum + value;
The same with value++;
value += 1;
could be more easily confused with
value += l; where l is a variable....
Its more about consistency that it is about right or wrong, but reducing code is a major bonus for maintainability.
Care must be taken with precendence of operators however, in complex statements.

In the case shown there's no particular reason to prefer one method of incrementing the value over another except perhaps for readability purposes. In this case I think I'd prefer sum += value over sum = sum + value as it's a bit briefer and (I think) clearer, but YMMV on that.
As far as prefering ++ over += 1, (IMO again) ++ is preferable when incrementing a value as part of an expression, e.g. sum += array[index++] - but if the entire point of what's being done is adding one to a value I'd prefer index += 1. But let's face it, a great deal of this is personal preference and spur-of-the-moment choice. I always try to write what I think, at that moment, is the simplest and clearest code possible - but I must admit that when I go back and read some of my own code later I have more "What was I thinkin'?!?" moments than I'd care to admit to. :-)
YMMV.
Best of luck.

Code A and B do the same thing. The advantage to using Code B is that it's quicker to type and easier to read.
As for using the ++ operator over += 1, again it is for readability. Although there is a difference between foo++ and ++foo. The former is read first and then incremented, while the latter is incremented first and then read from.

A compound assignment expression of the form E1 op= E2 is equivalent
to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1
is evaluated only once.
An example cited from Java's +=, -=, *=, /= compound assignment operators
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);

Its basically the same thing. Its both an operator.
One of it calls = and +. And the other +=..
So if you did value +=5. Value goes up by 5. += is better and more organized. And shortens your code whitch is better and more professional.

There is no difference between the two in terms of functionality. A += B actually means A = A + B. The first one is just a shorter way of writing the second.

They both are same up to that, both can be used for incrementing the value of a variable (stored in it).
x++ will increment the value of x by one (1) every run time.
+= adds right operand to the left operand and stores the result in left operand.
Something like following:
C += A is just same as C = C + A
The difference between both ++ and += is that the first can increment by one (1) only, while += can be used to increment more than one in just one line.
e.g:
x += 1; // will increment by 1 every run time
x += 4; // will increment by 4 every run time
x += 10; // will increment by 10 every run time

Related

c++ spaces in operators , what are the rules

Does spaces have any meaning in these expressions:
assume:
int a = 1;
int b = 2;
1)
int c = a++ +b;
Or,
2)
int c = a+ ++b;
When I run these two in visual studio, I get different results. Is that the correct behavior, and what does the spec says?
In general, what should be evaluated first, post-increment or pre-increment?
Edit: I should say that
c =a+++b;
Does not compile on visual studio. But I think it should. The postfix++ seems to be evaluated first.
Is that the correct behavior
Yes, it is.
Postfix ++ first returns the current value, then increments it. so int c = a++ +b means compute the value of c as the sum between current a(take the current a value, and only after taking it, increment a) and b;
Prefix ++ first increments the current value, then returns the value already incremented, so in this case, int c = a+ ++b means compute c as the sum between a and the return of the next expression, ++b, which means b is first incremented, then returned.
In general, what should be evaluated first, post-increment or
pre-increment?
In this example, it is not about which gets evaluated first, it is about what each does - postfix first returns the value, then increments it; prefix first increments the value, then returns it.
Hth
Maybe it helps to understand the general architecture of how programs are parsed.
In a nutshell, there are two stages to parsing a program (C++ or others): lexer and parser.
The lexer takes the text input and maps it to a sequence of symbols. This is when spaces are handled because they tell where the symbols are. Spaces really matter at some places (like between int and c, to not confuse with the symbol intc) but not others (like between a and ++ because there is no ambiguity to separate them).
The first example:
int c = a++ +b;
gives the following symbols, each on its own row (implementations may do this in slightly different ways of course):
int
c
=
a
++
+
b
;
While in the other case:
int c = a+ ++b;
the symbols are instead:
int
c
=
a
+
++
b
;
The parser then builds a tree (Abstract Syntax Tree, AST) out of the symbols and according to some grammar. In particular, according to the C++ grammar, + as an addition has a lower precedence than the unary ++ operator (regardless of postfix or prefix). This means that the first example is semantically the same as (a++) + b while the second is like a+ (++b).
For your examples, the ASTs will be different, because the spaces already lead to a different output at the lexer phase.
Note that spaces are not required between ++ and +, so a+++b would theoretically be fine, but this is not recommended for readability. So, some spaces are important for technical reasons while others are important for us users to read the code.
Yes they should be different; the behaviour is correct.
There are a few possible sources for your confusion.
This question is not about "spaces in operators". You have different operators. If you were to remove the space, you would have a different question. See What is i+++ increment in c++
It's also not about "what should be evaluated first, post-increment or pre-increment". It's about understanding the difference between post-increment and pre-increment.
Both increment the variable to which they apply.
But the post-increment expression returns the value from before the increment.
Whereas the pre-increment expression returns the value after the increment.
I.e.
//Given:
int a = 1;
int b = 2;
//Post-increment
int c = a++ +b; =>
1 + 2; (and a == 2) =>
3;
//Pre-increment
int c = a+ ++b; =>
1 + 3; (and b == 3) =>
4;
Another thing that might be causing confusion. You wrote: a++ +b;. And you may be assuming that +b is the unary + operator. This would be an incorrect assumption because you have both left and right operands making that + a binary additive operator (as in x + y).
Final possible confusion. You may be wondering why:
in a++ +b the ++ is a post-increment operator applied to a.
whereas in a+ ++b it's a pre-increment operator applied to b.
The reason is that ++ has higher precedence than the binary additive +. And in both cases it would be impossible to apply ++ to +.

Why are VB.NET and C++ giving different results for same expression?

Consider the following snippets:
C++:
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 20;
y = x + (x=y)*0;
cout << y;
return 0;
}
which gives a result of 20, because the value of y is assigned to x since the bracket is executed first according to the Operator Precedence Table.
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Integer = 10
Dim y As Integer = 20
y = x + (x = y) * 0
MsgBox(y)
End Sub
which instead gives a result of 10.
What is the reason for this difference?
What is the order of execution of operators in VB.NET?
Unlike in C++, VB.NET's = is not always an assignment. It can also be the equality comparison operator (== in C++) if it appears inside an expression. Therefore your two expressions are not the same. They are not even equivalent. The VB.NET code does not do what you might think it does.
First to your C++ code: Like you're saying, the assignment x=y happens first; thus your code is roughly equivalent to this: (It seems that was incorrect; see Jens' answer.) Since you end up with y being 20, it is likely that your C++ compiler evaluated your code as if you had written this:
int x = 10, y = 20;
x = y;
y = x + x*0; // which is equivalent to `y = 20 + 20*0;`, or `y = 20 + 0;`, or `y = 20;`
In VB.NET however, because the = in your subexpression (x=y) is not actually interpreted as an assignment, but as a comparison, the code is equivalent to this:
Dim x As Integer = 10
Dim y As Integer = 20
y = 10 + False*0 ' which is equivalent to `y = 10 + 0*0`, or `y = 10` '
Here, operator precedence doesn't even come into play, but an implicit type conversion of the boolean value False to numeric 0.
(Just in case you were wondering: In VB.NET, assignment inside an expression is impossible. Assignments must always be full statements of their own, they cannot happen "inline". Otherwise it would be impossible to tell whether a = inside an expression meant assignment or comparison, since the same operator is used for both.)
Your C++ snippet is undefined behavior. There is no sequence point between using x as the first argument and assigning y to x, so the compiler can evaluate the sub-expressions in any order. Both
First evaluate the left side: y = 10 + (x=y) * 0 -> y = 10 + (x=20) * 0 -> y = 10 + 20*0
First evaluate the right side: y = x + (x=20) * 0 -> y = 20 + 20 * 0
It is also generally a very bad style to put assignments inside expressions.
This answer was intended as a comment, but its length quickly exceeded the limit. Sorry :)
You are confusing operator precedence with evaluation order. (This is a very common phenomenon, so don't feel bad). Let me try to explain with a simpler example involving more familiar operators:
If you have an expression like a + b * c then yes, the multiplication will always happen before the addition, because the * operator binds tighter than + operator. So far so good? The important point is that C++ is allowed to evaluate the operands a, b and c in any order it pleases. If one of those operands has a side effect which affects another operand, this is bad for two reasons:
It may cause undefined behavior (which in your code is indeed the case), and more importantly
It is guaranteed to give future readers of your code serious headaches. So please don't do it!
By the way, Java will always evaluate a first, then b, then c, "despite" the fact that multiplication happens before addition. The pseudo-bytecode will look like push a; push b; push c; mul; add;
(You did not ask about Java, but I wanted to mention Java to give an example where evaluating a is not only feasible, but guaranteed by the language specification. C# behaves the same way here.)

Flip bool: performance comparison of x=!x versus x^=1

I am aware of two techniques for flipping a bool:
x = !x
and
x ^= 1
I prefer the second, in the same way that I prefer x++ over x+=1 over x=x+1.
But are they guaranteed to produce the same Assembly code?
And if not, is there some rationale to favour one over the other?
There are never any guarantees about same assembly code. Yes, given bool x, they both do exactly the same thing. Yes, that implies they are likely to be the same.
It is a common fallacy that writing expressions in an unusual way might make them faster. Avoid working with anyone who makes habits based on such ideas.
x = ! x is clearer because ! is defined in terms of Boolean values.
I prefer the second, in the same way that I prefer x++ over x+=1 over x=x+1.
Please prefer the first. It is expected and easily understood by most programmers. The second form, only works for values 0 and 1 in integer's case.
But are they guaranteed to produce the same Assembly code?
No.
And if not, is there some rationale to favour one over the other?
Decreasing the ratio of "wtf/loc" of you code (i.e. how many times would another developer look at your code and say "WTF?!?", over every n lines of code).
Edit: Either way, you will probably never see a real-world example of an application made faster by replacing one expression with the other. It is a matter of style, not a matter of performance.
The second expression is simply a source of difficulty found bugs. For example you may think that some expression has type bool while its actual type due to the integer promotion or usual arithmetic conversion is some integral type.
Consider the following code snippet
unsigned int x = 3;
x ^= 1;
std::cout << x << std::endl;
if ( x == false ) std::cout << "All is O'k\n";
else std::cout << "Oops. Something is wrong!\n";
x = 3;
x = !x;
std::cout << x << std::endl;
if ( x == false ) std::cout << "All is O'k\n";
else std::cout << "Oops. Something is wrong!\n";
So using expression x ^= 1; to flip a boolean value can only confuse readers of the code.
So I would prefer to use x = !x; instead of x ^= 1;
Do not forget about the principle KISS: Keep It Simple Stupid.:)
Though for example in C the result of operator ! has type int nevertheless the value of the operation is either 0 or 1.
From the C Standard
5 The result of the logical negation operator ! is 0 if the value of
its operand compares unequal to 0, 1 if the value of its operand
compares equal to 0.
So for both languages there is a guarantee that the result will be exactly either 0 or 1 for any source value.
!x and x^1 are clearly different operations.
The former is a logical negation, returning a 0/1 value. It makes sense to use it on bools.
The latter is a bitwise exclusive or, returning any possible value. It shouldn't be used on a bool. (For xoring bools, prefer the inequality comparison !=). It is also less efficient in unoptimized code as it invoves and extra operand (1).
K&R forgot to provide a !! operator, that you would have loved, and possibly ~~.

is it always faster to store multiple class calls in a variable?

If you have a method such as this:
float method(myClass foo)
{
return foo.PrivateVar() + foo.PrivateVar();
}
is it always faster/better to do this instead?:
float method(myClass foo)
{
float temp = foo.PrivateVar();
return temp + temp;
}
I know you're not supposed to put a call like foo.PrivateVar() in a for loop for example, because it evaluates it many times when you actually only need to use the value once (in some cases.
for (int i = 0; i < foo.PrivateInt(); i++)
{
//iterate through stuff with 'i'
}
from this I made the assumption to change code like the first example to that in the second, but then I've been told by people to not try to be smarter than the compiler! and that it could very well inline the calls.
I don't want to profile anything, I just want a few simple rules for good practice on this. I'm writing a demo for a job application and I don't want anyone to look at the code and see some rookie mistake.
That completely depends on what PrivateVar() is doing and where it's defined etc. If the compiler has access to the code in PrivateVar() and can guarantee that there are no side effects by calling the function it can do CSE which is basically what you've done in your second code example.
Exactly the same is true for your for loop. So if you want to be sure it's only evaluated once because it's a hugely expensive function (which also means that guaranteeing no side-effects get's tricky even if there aren't any) write it explicitly.
If PrivateVar() is just a getter, write the clearer code - even if the compiler may not do CSE the performance difference won't matter in 99.9999% of all cases.
Edit: CSE stands for Common Subexpression eliminiation and does exactly what it stands for ;) The wiki page shows an example for a simple multiplication, but we can do this for larger code constructs just as well, like for example a function call.
In all cases we have to guarantee that only evaluating the code once doesn't change the semantics, i.e. doing CSE for this code:
a = b++ * c + g;
d = b++ * c * d;
and changing it to:
tmp = b++ * c;
a = tmp + g;
d = tmp * d;
would obviously be illegal (for function calls this is obviously a bit more complex, but it's the same principle).

Simple Operator question. +=

So my friend gave me some source code to start out with so I could review and understand it and I have a question about it, but since he's not online I thought I would try here, mainly I don't quite understand this line.
num += i;
Essentially, this is the same as
num = num + i
right?
If you need more details please tell me! I look forward to hearing your replies soon.
From ISO C++03 (Section 5.17/7)
The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.
Essentially yes, but it is more efficient. For basic types, like integers, using num += i increments the value of num directly, whereas num = num + i creates a temporary of the value of num, increments it, and then assigns it back to num.
Yes. It is exactly the same (assuming you are talking about the built-in +=). In fact, this is how += is defined in the language specification.
Doesn't your favorite C++ book cover this topic?
What will really happen there, as posted before, depends on the language. If one assumes C++, and that num is an integer, then as others have posted and as you have
num += i;
is equivalent to
num = num + i;
But it is really up to the class to determine that behavior in c++ / c#. You will essentially call the "+=" operator on the num object for the i object type. This should, in a good design, be the same as first performing the "+" operator, and then performing the = operator in the manner above. But it doesn't have to be:
class foo
{
bool operator += (int i) {return false;}
}
foo num;
int i;
bool result = num += i;
In that example, num will be unchanged, and result will be false.