I'm not really sure what's happening here and when 1 is being added to each variable. I was wrote this to try to understand it but i'm still confused. Can someone please explain whats happening.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
int y = 2;
int x = y++;
cout << x << endl; //prints 2
++x;
cout << x << endl; //prints 3
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int x = 2;
int y = x++; // Takes the Cuurent value of x assignes it to y and then increments x
int z = ++x; // Increments x and then assignes the new value to z
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
for (int i=0; i < n; i++)
doSomething();
// is the same as
int i=0;
while (i < n)
{
doSomething();
i++;
}
// which is the same as
int i=0;
while (i < n)
{
doSomething();
++i;
}
// which is the same as
for (int i=0; i < n; ++i)
doSomething();
Generally speaking, if only used in a single term expression, the prefix increment operator is preferred because it has less overhead to its use. That being said, the increased efficiency of ++i over i++ is quite small. In the examples of the for loops increment expression, both perform exactly the same logically speaking. The real concerns are when they are used in multi-term expressions and statements as shown above.