I thought that my understanding of side effects in programming languages was OK.
I think this is a great definition from wikipedia:
"in addition to returning a value, it also modifies some state or has
an observable interaction with calling functions or the outside world."
However, I read this in the same link(yes, I know that is probably not the best place to look for examples):
"One common demonstration of side effect behavior is that of the
assignment operator in C++. For example, assignment returns the right
operand and has the side effect of assigning that value to a variable.
This allows for syntactically clean multiple assignment:"
int i, j;
i = j = 3;
Why do they consider that a side-effect? It is the same as two simple assignment statements to 2 local variables.
Thanks in advance.
You can use an assignment expression as a value:
double d = 3.5;
int x, y;
printf("%d", x = d); // Prints "3".
y = (x = d) * 5; // Sets y to 15.
double z = x = d; // Sets z to 3 (not 3.5).
The value produced by x = d, is its main effect. The changing of the value of x is a side effect.
If the state of the world, for example the value of a variable, is modified in a calculation, it's a side effect.
For example, j = 3 calculates 3, but it also modifies the value of j as a side effect.
A less trivial example: j += 3 calculates j + 3, but it also sets j to this new value.
The semantics of C muddle the waters: in C the main point of writing i = 1 is to get the side effect of the variable assignment; not calculating the value 1. The talk about assignments as side effects makes more sense with functional programming languages such as Haskell or Erlang, where variables can only be assigned once.
I would presume that to be because j = 3 has the intended effect of assigning the value 3 to j but also has the side effect of returning the value of j
Related
Why does an expression i = 2 return 2? What is the rule this is based on?
printf("%d\n", i = 2 ); /* prints 2 */
I am in C domain after spending long time in Java/C#. Forgive my ignorance.
It evaluates to 2 because that's how the standard defines it. From C11 Standard, section 6.5.16:
An assignment expression has the value of the left operand after the assignment
It's to allow things like this:
a = b = c;
(although there's some debate as to whether code like that is a good thing or not.)
Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too).
The rule is to return the right-hand operand of = converted to the type of the variable which is assigned to.
int a;
float b;
a = b = 4.5; // 4.5 is a double, it gets converted to float and stored into b
// this returns a float which is converted to an int and stored in a
// the whole expression returns an int
It consider the expression firstly then print the leftmost variable.
example:
int x,y=10,z=5;
printf("%d\n", x=y+z ); // firstly it calculates value of (y+z) secondly puts it in x thirdly prints x
Note:
x++ is postfix and ++x is prefix so:
int x=4 , y=8 ;
printf("%d\n", x++ ); // prints 4
printf("%d\n", x ); // prints 5
printf("%d\n", ++y ); // prints 9
Assign the value 2 to i
Evaluate the i variable and display it
In C (almost) all expressions have 2 things
1) a value
2) a side effect
The value of the expression
2
is 2; its side effect is "none";
The value of the expression
i = 2
is 2; its side effect is "changing the value in the object named i to 2";
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
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.)
In some C++ sources I saw that an expression result can be saved as a constant reverence. Like this:
const int &x = y + 1;
What does it mean?
Is there any documentation on this? I can't find it..
For me it seems to be equivalent to:
const int x = y + 1;
since result of the program stays the same. Is it truly equivalent?
If yes why does the language allows the first way to write it at all? It looks confusing.
If no what is the difference?
The difference should be whether or not the result is copied/moved. In the first case:
const int& x = y + 1;
The value of y+1 is essentially saved as a temporary value. We then initialize a reference x to this temporary result. In the other case:
const int x = y + 1;
We compute y + 1 and initialize a constant variable x with the value.
In practice with integers there will be no visible difference. If y+1 happened to be a large data structure, e.g., a class which is 1MB of data, this could make a significant difference.
What is the output of the following code:
int main() {
int k = (k = 2) + (k = 3) + (k = 5);
printf("%d", k);
}
It does not give any error, why? I think it should give error because the assignment operations are on the same line as the definition of k.
What I mean is int i = i; cannot compile.
But it compiles. Why? What will be the output and why?
int i = i compiles because 3.3.1/1 (C++03) says
The point of declaration for a name is immediately after its complete declarator and before its initializer
So i is initialized with its own indeterminate value.
However the code invokes Undefined Behaviour because k is being modified more than once between two sequence points. Read this FAQ on Undefined Behaviour and Sequence Points
int i = i; first defines the variable and then assigns a value to it. In C you can read from an uninitialized variable. It's never a good idea, and some compilers will issue a warning message, but it's possible.
And in C, assignments are also expressions. The output will be "10", or it would be if you had a 'k' there, instead of an 'a'.
Wow, I got 11 too. I think k is getting assigned to 3 twice and then once to 5 for the addition. Making it just int k = (k=2)+(k=3) yields 6, and int k = (k=2)+(k=4) yields 8, while int k = (k=2)+(k=4)+(k=5) gives 13. int k = (k=2)+(k=4)+(k=5)+(k=6) gives 19 (4+4+5+6).
My guess? The addition is done left to right. The first two (k=x) expressions are added, and the result is stored in a register or on the stack. However, since it is k+k for this expression, both values being added are whatever k currently is, which is the second expression because it is evaluated after the other (overriding its assignment to k). However, after this initial add, the result is stored elsewhere, so is now safe from tampering (changing k will not affect it). Moving from left to right, each successive addition reassigns k (not affected the running sum), and adds k to the running sum.