Tuesday 25 December 2012

C/C++ Puzzles: PART - 8


The Problem with Side Effects in C/C++

  What is a side effect in a programming language? Well it is defined as the result of an operator, expression, statement, or function that persists even after the operator, expression, statement, or function has finished being evaluated. 

x=10;
x++;

The increment operator changes the value of x permanently. After the statement has finished executing, x will have the value 11. This is an example for side effects.

x=10;
cout<<(x+1);

There is no side effect here. The output will be 11. But the value of x is still 10.

The problem with side effects is that in C/C++ there is no standard order of evaluation as far as the left and right side of a single operator is concerned. For example in the statement C=A+B we don't know whether A will be accessed first or B will be accessed first. In some situations we might get unexpected results due to this. Consider the code given below.

a=10;
b=(++a * 2)+(++a * 4);
printf("Value is %d\n",b);

If the left hand side of the operator + is evaluated first we will get 70 as output. If the right hand side is evaluated first the output will be 68. Try the program on different compilers and you will understand the problems with side effects in C/C++. 

No comments:

Post a Comment