What does the ++counter mean?

9.9k Views Asked by At

I don't consider myself to be bad at programming, but there's been something troubling me since the past few days.

int counter = 3;
++counter;

Is the following code above the same as counter++;.

1

There are 1 best solutions below

2
On BEST ANSWER

It is similar, but not the same.

In your expression it doesn't matter, but if you had something more complicated, like System.out.println(counter++), it would make a big difference.

For example: int counter = 3; System.out.println(counter++)

This will print 3, then increment counter to 4.

However, if you do

int counter = 3; System.out.println(++counter)

it will print 4 because it increments prior to giving the value as a parameter to the print function.

It's a question of when the increment is performed, the prefix performs it before other operations, postfix performs it after. They have different precedences.