What makes the increment and decrement operator so different

Nov 1, 2011 at 4:27am
Hi all,

A C++ newbie here. As a beginner, I like to play around with different syntax of the language and sometimes I'm faced with situations, such as the one below, that I can't get a hang of.

In the first code below, I observed that the expression "myarray[i]+1" inside the for-loop doesn't change the elements of the array.

1
2
3
4
5
6
7
8
9
10
11
12
int* DoubleArray (int* myarray, int size)
{
    int* p;
    p=new int[size];

    for(int i=0;i<size;i++)
    {
        p[i]=myarray[i]+1;
    }

    return p;
}


However, if I have:

1
2
3
4
5
6
7
8
9
10
11
12
int* DoubleArray (int* myarray, int size)
{
    int* p;
    p=new int[size];

    for(int i=0;i<size;i++)
    {
        p[i]=myarray[i]++;
    }

    return p;
}


Each element are truely incremented by one. What makes the increment/decrement operator so different from the ordinary addition/substraction of one to/from the variable.

Thanks in advance.
Nov 1, 2011 at 4:49am
Pretty much how you've shown yourself. The increment/decrement operators increment/decrement the variable they are attached to.
Nov 1, 2011 at 4:50am
The increment operator is actually "add 1 and assign it to the original variable". Whereas the + operator just adds 1.

Examples:

1
2
3
4
5
6
7
int foo = 5 + 3;  // foo = 8.  This does not change '5'
int bar = foo + 2;  // bar = 10.  This does not change 'foo', which is still 8

bar++;  // this increments bar, so it is now 11

bar += 5;  // this adds 5 and assigns it to bar, so it is now 16
  // same as "bar = bar + 5;" 
Nov 1, 2011 at 6:02am


Thanks LBEaston and thanks to Disch, too, for your explanation.
Topic archived. No new replies allowed.