Also for a better understanding you can consider these loosely described examples:
- think of the pre-increment for
the_object
of the_type
as a function like this:
the_object = the_object + 1;
return the_object;
- now think of the Post-increment for
the_object
of the_type
as a function like this:
the_type backup_of_the_object;
backup_of_the_object = the_object;
the_object = the_object + 1;
return backup_of_the_object;
Now consider:
result = counter++ + 10;
When the program is being compiled:
- compiler sees
result =
at the beginning of the line, so it
should first determine what is placed at the right side of =
and then produce the machine code to assign it to the left side of
=
which is result
.
- compiler sees
counter
but the statement has not ended
because;
has not been reached yet. So now it knows that it
also has to do something with counter
.
compiler sees ++
but the statement has not ended. So now it
knows that it has to consider producing the machine code to perform
counter++
first.
compiler sees +
. So now it knows that it has to consider
producing the machine code to add the right side of +
and the
left side of +
which was counter++
.
compiler sees 10;
and finally the statement has ended. So now
it knows all that it needed to know! It knows that after producing
the machine code to perform counter++
, it should produce the
machine code to add 10 to the outcome_of it. Then it should
produce the machine code to assign the outcome_of that to the
result
.
when the program is running:
- CPU should perform
counter++
now counter
is incremented by 1 hence it is 11 but the outcome_of(counter++
) is the previous value of the counter
which is 10
- CPU should perform outcome_of(
counter++
) + 10
now outcome_of(outcome_of(counter++
) + 10) is outcome_of(10 + 10) which is 20
- CPU should perform
result =
outcome_of(outcome_of(counter++
) + 10)
now result
is 20
Also please note that every stages that was described was only about
result = counter++ + 10;
regardless of what is going to happen afterwards. Meaning before
cout << "Counter: " << counter << endl;
cout << "Result: " << result << endl;
so obviously before main()
returns 0.
In my opinion you should take it easy and learn it through experience by writing and running some programs!
Good luck!