Friday, November 7, 2008

One interesting problem in C++

Take every community or forums on c++ they will have a tricky question like this.why is this so why what is the output ? One of my friends also had such a doubt..

" When I compile & run this code in Linux, AIX and Solaris I got different outputs.

int i=10;
cout<<<<--i;


In Solaris and AIX (both g++) I got 101010 as output but in Linux I got it as 10999. I think the order of evaluation is different in Linux when compared to Solaris and AIX.

Let me know if you have better explanations. "

Well here is my
explanation
The C++ language says that you cannot modify a variable more than once between sequence points.
The C++ standard says
"At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. "
Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.
So in fact it means u cant modify the same value twice between 2 sequence points. If u do so, the result is undefined and depends on the compiler implementation.

The "certain specified points" that are called sequence points are

  • the semicolon
  • the non-overloaded comma-operator
  • the non-overloaded || operator
  • the non-overloaded && operator
  • the ternary ?: operator
  • after evaluation of all a function's parameters but before the first expression within the function is executed
  • after a function's returned object has been copied back to the caller, but before the code just after the call has yet been evaluated
  • after the initialization of each base and member

No comments: