Re: i++ or ++i ?
John Brawley wrote:
...
#include <iostream>
int main() {
for(int i=0; i<10; i++)
std::cout<<i<<", ";
std::cout<<"\n";
for(int i=0;i<10;++i)
std::cout<<i<<", ";
std::cout<<"\n";
int b=7;
b++; std::cout<<b;
int c=7;
++c; std::cout<<"\n"<<c;
//????????? why? same outputs!
return 0;
}
_Same_output_.
What's the difference?
(I use these in a program, which doesn't crash....)
...
Both 'i++' and '++i' in C++ are _expressions_. Any non-void expression
in C++, has a result (i.e. what it evaluates to) and, possibly, some
side effects. When someone tells you that prefix increment happens
"before" and postfix increment happens "after", it really means that the
result of '++i' expression is the "new" value of 'i' (the value "after"
the increment), while the result of 'i++' expression is the "old" value
of 'i' (the value "before" the increment). This means that in order to
see the difference between '++i' and 'i++' you have to inspect the
_results_ of these expressions. The code you wrote does not use these
results in any way, it completely ignores them. No wonder you can't see
any difference.
To inspect the results of '++i' and 'i++' you have to store them and
output them later (or output them right away) instead of discarding
them. For example:
int i, a, b;
i = 0;
a = ++i; // store the result of pre-increment
i = 0;
b = i++; // store the result of post-increment
Now take a look at the values of 'a' and 'b' an you'll see the difference.
--
Best regards,
Andrey Tarasevich