2

My question is how come when we use ++ in a 'for loop' (++ on the right side) it increases. And in this example its on the right side but it does not increase.

int a = 1, y;
b = a++; //so "b" will be 1
         // if we do ++a then "b" will be 2
tripleee
  • 175,061
  • 34
  • 275
  • 318
sup
  • 23
  • 1
  • 4
  • 1
    Question isn't clear. Give more explanation – Vikas Verma Oct 06 '14 at 09:14
  • possible duplicate of [Why doesn't changing the pre to the post increment at the iteration part of a for loop make a difference?](http://stackoverflow.com/questions/1918196/why-doesnt-changing-the-pre-to-the-post-increment-at-the-iteration-part-of-a-fo) – The Archetypal Paul Oct 06 '14 at 09:25
  • Duplicates about a million other questions. Specifically, this answer to the one I noted as duplicate http://stackoverflow.com/a/3511075/21755 pretty much sums it up – The Archetypal Paul Oct 06 '14 at 09:25

3 Answers3

3

It increases in both the for loop and in your example. a++ increases a, but b gets the previous value of a.

In a for loop you don't assign the return value of i++ to a different variable, so it doesn't matter if you write i++ or ++i.

for (int i=0;i<5;i++)
{
    System.out.println(i);
}

and

for (int i=0;i<5;++i)
{
    System.out.println(i);
}

Will behave exactly the same.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

In both cases, the value of a increase. However, with b = a++;, the value of a increase after its original value has been assigned to b but with b = ++a; the value of a increase before its value is assigned to b.

The distinction is not with the value of a beeing increased or not; it is for the value that is assigned to the variable b: the original value before the increase of a or the new value after its increase.

If there is no assignment of a to some other variable, then there is no difference between a++ and ++a.

SylvainL
  • 3,926
  • 3
  • 20
  • 24
0

in a++, the value of a is incremented after the execution on statement i.e while execution of statement the value is not incremented but is incremented AFTER its execution .

in ++a, the value of a is incremented during the execution of statement i.e while execution we get the incremented value as the result.