Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment ++i, i++ and i+=1

I am beginner in C++. What I understand is that:-

i++ is executing first, then increment, ++i is increment first, then execute,i+=1 is increment by 1,then execute. But in the FOR loop:

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

There is really no difference in these two loops above.

Here is another one to calculate the sum of all integers from 1 to 100:

int i=1, sum=0;
while (i<=100)
{
    sum+=i;
    i++;         //i+=1;    ++i;
}
cout<<sum<<" "<<i<<endl;
return 0;

But if I replace i++ with i+=1 or ++i, they all return a sum of 5050 and i of 101. So I really don't see any difference in them.

So could anyone explain this to me? Which one of those is used most in programming? Thank you!!

like image 852
user3858 Avatar asked Jan 21 '26 09:01

user3858


1 Answers

You are correct. In your examples there is no difference.

But here there is:

int i = 0;
cout << i++ << endl;  //prints 0
cout << i   << endl;  //prints 1

vs

int i = 0;
cout << ++i << endl;  //prints 1
cout <<   i << endl;  //prints 1

Which one of those is used most in programming?

Most of the time, ++ is the only operation in the statement (FYI, a for loop has three statements).

If it isn't, then it might matter, and you'll use whichever one gives you the correct behavior.

FYI

Some developers have the opinion that if pre and postfix operators should always be used alone (not part of a large statement). They can lead to confusing code, or even undefined behavior.

For example,

int i = 0;
cout << i++ + i++ << endl;

has undefined behavior.

like image 199
Paul Draper Avatar answered Jan 27 '26 02:01

Paul Draper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!