Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   pre increment & post increment (http://www.go4expert.com/forums/pre-increment-post-increment-t24001/)

cindrilla 26Nov2010 21:38

pre increment & post increment
 
hi frinds pls let me know wht will be d mechanism of preincrement & post increment i have got the basic idea of these terms but when i had come to htis pariticular question im going wrong so y is it pls anyone can help me
c=(++a)+(++a)+(a++)+(a++);
then if i assume a=5
then
then i will get c as
c=6+7+7+8
which is equal to 28 but it is showing as 27 y so?

ThorAsgard 27Nov2010 03:51

Re: pre increment & post increment
 
Quote:

Originally Posted by cindrilla (Post 75237)
hi frinds pls let me know wht will be d mechanism of preincrement & post increment i have got the basic idea of these terms but when i had come to htis pariticular question im going wrong so y is it pls anyone can help me
c=(++a)+(++a)+(a++)+(a++);
then if i assume a=5
then
then i will get c as
c=6+7+7+8
which is equal to 28 but it is showing as 27 y so?


Just tried this in Microsoft Visual Studio 2010 C++

Code:


#include <iostream>
using namespace std;
 
int main()
{
int a = 5;
int c = 0;
c = (++a)+(++a)+(a++)+(a++);
cout << "Resulting value : " << c << endl;
return 0;
}

And result 28
:happy:

xpi0t0s 29Nov2010 13:52

Re: pre increment & post increment
 
Behaviour is undefined as the exact time the post increment is performed is not specified.

In Visual Studio, c=(++a)+(++a)+(a++)+(a++); is equivalent to
++a; ++a; c=a+a+a+a; a++; a++;
which would give the result 28.

But other compilers (including other versions of Visual Studio) might differ, and it is perfectly OK for a compiler to interpret this code as
c=++a (preincrement a from 5 to 6 then take the value: 6)
+ ++a (preincrement from 6 to 7 then take the value: 7)
+ a++ (take the value 7 then post increment a to 8)
+ a++ (take the value 8 then post increment a to 9)
which would be equivalent to c=6+7+7+8, which is also 28.

and there could be other interpretations, such as the one you use to get 27. So the answer to this is not to abuse pre- and post-increment operators in this way; do not use the same variable more than once in an expression if you are going to pre- or post-increment it.

ichandu 29Nov2010 14:08

Re: pre increment & post increment
 
The c variable is set as =0;
then calculate you get 28.

thanks.


All times are GMT +5.5. The time now is 18:57.