Typically the code that I have seen uses phrases such as i++ as opposed to ++i. Recently, in a recently purchased book, I have seen the former implemented.

As I understand i++ means that the addition takes place after the line is executed and thus with the initial value of i. Furthermore, ++i means that 1 is added to i before the line is executed, thus changing altering the value of whatever i was used to calculate.

for example:
int i = 4
x = i++ * 10. x would be equal to 40. only after the line is executed does i equal 5.

However, in the code
int i = 4
x = ++i * 10., x would be equal to 50, because i takes on the value of 5 before the line is executed.

This all brings me to my conundrum. What is the difference between the following two lines of code:

for (int i = 0; i < something; i++)
{}
and
for (int i = 0; i < something; ++i)
{}

I'm going to take a guess that that final addition to i always takes place after the code inside the brackets is executed. This would lead to me believe that the two lines are identical; however, I somehow doubt this is the case. Can someone give me hand? Thank you very much.

Recommended Answers

All 2 Replies

You're right. The two lines are identical.

Let's take for(int i =0 i <10; i++) { //do stuff} for example.
another way to write this code is:

int i=0
while (i< 10)
{
    // do stuff
    i++;
}

As you can see in the code above, it doesn't matter if you write i++ or ++i. As long as it gets incremented by one.
Here's another example to ake things clearer:

#include <iostream>
#include <string>

using namespace std ;

int main()
{

    for (int i = 0; i < 10; i++)
        cout << i;

    cout << endl;

    for (int i = 0; i < 10; ++i)
        cout << i;

    cout << endl;
    
    int i =0;
    while (i < 10)
    {
        cout << i;
        i++;
    }
    cout << endl;

    i =0;
    while (i < 10)
    {
        cout << i;
        ++i;
    }
    return 0;
}

will output:

0123456789
0123456789
0123456789
0123456789

The only difference is that for

i++, the compiler creates a temporary (the value of i before the incremental) for use.

I'm sure that most compilers now optimse the situation where the temporary is not needed and hence this is no longer an issue

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.