confuse on i++ and ++i

Hi, everyone i know this is easy for you but i just have no idea about the difference between i++ and i--..
see the following code,

#include <iostream>
using namespace std;

int main()
{int i = 4, j = 25,
3 + ++i;
10 – i++;
cout << 5 * i-- + j;
}
the output is 55 but i have been confused with the increment.. could anyone explain how it is being calculated and how it runs?
thanks..

These two expressions

3 + ++i;
10 – i++;

has side effects of increasing i. In these statements it is not important whether a postfix or prefix operators are used because the results of the expressions are not used. But in any case i will be equal tp 6 because it will be increamented twice.

Now consider the following statement

cout << 5 * i-- + j;

In this statement i-- is a postfix operator so the value of i-- will be the value before decreasing i. So we have 5 * 6 + 25 == 55. i becone equal to 5 after the call of the operator << that is the side effect will be applyed after the call.
I believe that this is the case:

1
2
3
4
5
6
int i = 0;
int array[2] {0};
array[++i] = 3; // i read as 1, incremented BEFORE reading.
// i == 1.
array[i++] = 4; // i read as 1, incremented AFTER reading.
// i == 2 
closed account (zb0S216C)
The postfix increment/decrement operator will increment/decrement its operand (the piece of data the operator is used on). Before the operand, "i", is incremented/decremented, a copy of the operand is made which is returned to the user. The result of the postfix increment/decrement will be the original value of "i" and the next time you read the value of "i" it will have been incremented/decremented.

The prefix increment/decrement operator will increment/decrement its operand by one and then return the resulting value.

Here's some code to help clear things up:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
// POSTFIX
//
int X( 10 );
int Y( X++ ); // Y will be == 10, not 11.

int A( 10 );
int B( A-- ); // A will be == 10, not 9

//
// PREFIX
//
int C( 10 );
int D( ++C ); // D will be == 11, not 10

int E( 10 );
int F( --E ); // F will be == 9, not 10. 

Wazzak
Last edited on
Topic archived. No new replies allowed.