-4

I want to pre-increment a value assignment in a for loop

for (int x=0; x<100; x+=increase){
   // loop operation here
}

The code above post increments the value, however I want to pre increment it. I know I can pre-increment by one with the ++i syntax, however is there a way to pre increment through variable assignment.

Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
  • 2
    I don't know what you mean by "pre-increment". Assignment is effectively "pre" in that it returns the new value of the variable. – melpomene Jul 25 '19 at 16:52
  • 3
    Replace `x=0` with `x=increase`, if that's what you're trying to do. – Thomas Jager Jul 25 '19 at 16:52
  • 1
    Post- and pre- increment are only meaningful if you use the value of the assignment expression for something, like assigning it to another variable or passing it to a function. You're not doing that here, you're just incrementing the variable and nothing else, so any way you do that is equivalent. – Lee Daniel Crocker Jul 25 '19 at 20:23

1 Answers1

6

It sounds like you have two misconceptions.

  1. x += y is already "equivalent" to preincrement, in that x += 1 is, by definition, identical to ++x. (The point is that the value of x += y is the updated value of x, just as the value of ++x is the updated value.) It's the postincrement form x++ that has no exact equivalent for adding increments other than 1.
  2. When you write for(x = 0; x < 100; x += increase), you're not immediately using the value of the expression x += increase, so it doesn't matter if you use a preincrement or postincrement form.

If you want your loop to start with an initial value of increase rather than 0, just write

for(x = increase; x < 100; x += increase)
melpomene
  • 84,125
  • 8
  • 85
  • 148
Steve Summit
  • 45,437
  • 7
  • 70
  • 103