Simple Operator question. += - c++

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.

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

+= Operator in 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

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

Why the addtion of ++overloaded operation results into unexpted values?

See the code
#include<iostream.h>
#include<conio.h>
class A{
private:
int i;
public:
A()
{
i=10;
}
A operator++(int)
{
A tmp=*this;
i +=1;
return tmp;
}
display()
{
cout<<i;
}
};
int main()
{
A a,b;
b=a++ + a++;
cout<<endl<<b<<"\t"<<a;
return 0;
}
For the statement b = a++ + a++, the expected value we think will be 20,
But the above statement resulted into 21.
How?
Kindly help me out.
According to cppreference, your code is equals to b = (a++) + (a++)
So, computing it, we have:
a = 10;
tmp1 = a++;//tmp1 = 10, a = 11
tmp2 = a++;//tmp2 = 11, a = 12
b = tmp1 + tmp2 // 10 + 11 = 21
Also remember that constructions like b = a++ + a++; are very poor readable, so you should always use brackets, also it's always a good idea to avoid using increments and decrements like a++ in complex expressions. Readability is much better than showing that you know operator priorities.
As Charles pointed out ++ called on A object are function calls. Thus you first increment i from 10 to 11 and return 10, then in the second call you increment i from 11 to 12 and return 11. The you add 10 and 11 ending up with 21.
The first call increments a to 11 and returns 10. The second call increments a to 12 and returns 11. Sounds like 21 is correct.
That said, the order of evaluation (which ++ is "the first call") is unspecified (thanks JD), so using it twice in the same expression is generally not a good idea.
I shall render my answer in the form of a simple comparison.
Your code is:
b = a++ + a++;
I think you rather confused it with:
b = a + (a++)++;
Overloaded operators are just functions with funny names. They don't neccesarily behave the same as built-in ones. If you're tempted to do the same expression with an object of built-in type - don't, the behaviour would be undefined.
You haven't shown the definition of operator+ for A - I'll asume it's a free function. The expression b = a++ + a++; can then be rewritten as
b = operator+( a.operator++(0), a.operator++(0) );
Hope that helps make things clearer.
The two calls to postfix increment are indeterminately sequenced - that means we can't know which one will be called first. It doesn't matter in your case, since they're both called on the same object, but don't rely on any particular order - it need not be consistent, even during the same execution of the program.

C++ Conditional Operator

I once seen a -wired- operator in C++ which assigns value if greater than..
it was a combination of ?, < and =
e.g. let x = value if value is greater than x
I do not mean x=(x<value)x:value
It was some sort of x<?=value
But I can not remember it exactly, and can not find it online... Can some one remind me of it?
Thanks,
There is no operator that assigns variables based on their relative values.
However, there is the ?: operator:
x = value > x ? value : x;
If you read it out loud from left to right, it makes sense.
gcc has -- in version 3.3.6 at least! -- a gcc-specific language extension providing specialized operators for implementing min and max. Perhaps this is what you are thinking of?
Minimum and Maximum Operators in C++
I don't have gcc handy to test it with, but it might have an updating form, too.
How's that:
(x<value) || (x=value)
Are you thinking of the ternary operator?
result = a > b ? x : y;
I suspect what you're thinking of is a gcc extension1 that lets you leave out the middle operand to the conditional operator, so (for example):
a = b ? b : c;
can be written as:
a = b ?: c;
1 Despite the '2.95.3' in the URL, I'm not aware of a newer version of the linked page. If somebody is, please feel free to point it out (or edit it in).
it's a more convenient version of an if statement that is used for assignment
int x = (some bool) ? trueval : falseval;
this is roughly what it means, when the bool is evaluated it either gets the trueval or falseval depending on the outcome, it's easier than saying
int x;
if (someval)
x = trueval;
else
x = falseval;
x = x < value ? 0 : 1;
This function sets x to 0 is x < value, 1 otherwise.