the difference between p++, ++p, p-- and --p

hello, as the tittle says i have a simple question.
Our teacher told us that there is a difference between those ++ and --, when used as prefix or postfix in a code.
so could someone explain me in detail what is the diference and give me an example if possible.
I tried myself to figure out the difference but i got the same result for both for ex. "p++" and "++p".
For built-in types, if these were functions, "as-if"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int& prefix_increment( int& lvalue ) // ++lvalue: return reference
{
    // step 1. side effect
    lvalue = lvalue + 1 ; // increment the lvalue

    // step 2. value computation
    return lvalue ; // return reference to the incremented value
}

int postfix_increment( int& lvalue ) // lvalue++: return prvalue
{
    // step 1. value computation
    int temp = lvalue ; // create a temporary holding a copy of the lvalue (before it is incremented)

    // step 2. side effect
    prefix_increment(lvalue) ; // increment the lvalue, discard the result

    // return the value computed in step 1.
    return temp ; // return the temporary (which holds a copy of the original value)
}
See how the bahavior differs between pre- and post- incrementing/decrementing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

int main()
{

	int x = 10;

	// increment before use
	std::cout << "pre-increment:  " << ++x << std::endl;	// prints 11
	std::cout << "result:         " << x << std::endl;	// prints 11
	std::cout << std::endl;

	// use first, then increment
	std::cout << "post-increment: " << x++ << std::endl;	// prints 11
	std::cout << "result:         " << x << std::endl;	// prints 12
	std::cout << std::endl;

	// decrement before use
	std::cout << "pre-decrement:  " << --x << std::endl;	// prints 11
	std::cout << "result:         " << x << std::endl;	// prints 11
	std::cout << std::endl;

	// use first, then decrement
	std::cout << "post-decrement: " << x-- << std::endl;	// prints 11
	std::cout << "result:         " << x << std::endl;	// prints 10
	std::cout << std::endl;

	return 0;
}
An example in which they make a difference is in this for loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main()
{
    //PRINTS 9-0, thus 10 times
    for (int cycle = 10; cycle--; ) {
        std::cout << "POST INCREMENT: " << cycle << "\n";
    }
    std::cout << '\n';
    
    //PRINTS 9-1 thus 9 times
    for (int cycle = 10; --cycle; ) {
        std::cout << "PRE INCREMENT: " << cycle << "\n";
    }
    std::cin.get();
    return 0;
}
Topic archived. No new replies allowed.