Difference between

in the increment of a for loop, I don't know the difference between ++t and t++.

Is there one?
closed account (N85iE3v7)
++t is a post incremental operator, thus it will increment before it is used in something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
// suppose t = 1

while ( ++t  != 10 ) // the comparison will be 2 != 10 
{
    // it is now t = 2 during first iteration
}

// whereas

t = 1;
while ( t++ !=  10 ) //  is 1 != 10 ?
{
  // t = 2 as well but the comparison was different
}



Check here:

http://www.cplusplus.com/doc/tutorial/operators/


Specially this part:


A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression.


The example there is much better than mine :-)

++t -> first make incrementation of t and then make something else....
t++ -> after current code increment t

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
        int a=0;
        std::cout << a << std::endl;
        std::cout << a++ << std::endl;
        std::cout << a << std::endl;
        std::cout << ++a << std::endl;
        std::cout << a << std::endl;
        return 0;
}

gives...
0
0
1
2
2
closed account (DSLq5Di1)

++x == x = x + 1

x++ == tmp = x, x += 1, tmp

x++ will create a temporary to store the original value, increment x, then return tmp.

If you are not using the returned temporary, as in the case of for(int i = 0; i < max; i++), there is little functional difference between them.

The reason ++x may be preferred over x++ is to avoid an unnecessary temporary, although most modern compilers will make this optimization for you.
Topic archived. No new replies allowed.