-1

I am using Swift2 and i have these two loops:

for var i: Int = 0; i < 4; i++ {
    print("the i = \(i)")
}

and 

for var i: Int = 0; i < 4; ++i {
    print("the i = \(i)")
}

I got the exact same print in both of them. Why please?

Carol Smith
  • 199
  • 1
  • 1
  • 16

3 Answers3

11

i++ and ++i do the same thing in this case; increment i by one. The difference between them is that they return different values, which doesn't matter in your loop because the return value for the 'increment' part is ignored.

i++ (known as 'post-increment') returns the value of i before it was incremented, whereas ++i (known as 'pre-increment') returns the value of i after it was incremented. For example:

var i = 1

print(i++) // Prints 1, i is now 2

print(++i) // Prints 3, i is now 3

Traditionally, the pre-increment (++i) was slightly faster because it didn't have to remember the previous value of i after incrementing it when it returned the value, but I doubt there is any difference in modern compilers.

Robert
  • 5,735
  • 3
  • 40
  • 53
2

According to Swift Manual the syntax of the for statement is:

for initialization; condition; increment {
    statements
}

and what happens is if the condition is true, then the statements will be executed, not the increment that is why you are having the same results

Please read this:

A for statement is executed as follows:

  1. The initialization is evaluated only once. It is typically used to declare and initialize any variables that are needed for the remainder of the loop.

  2. The condition expression is evaluated. If true, the program executes the statements, and execution continues to step

  3. If false, the program does not execute the statements or the increment expression, and the program is finished executing the for statement. The increment expression is evaluated, and execution returns to step 2.
William Kinaan
  • 28,059
  • 20
  • 85
  • 118
0

++i and i++ are expressions meaning increment i by one, but ++i means perform the increment before the expression is used while i++ means perform the increment after use.

In a for loop the evaluation of the increment expression happens after the code in the block is executed so, in your examples, it does matter which you use.

To see the difference, try these:

var j: Int = 0
for var i: Int = 0; i < 4; i++ {
    print("the i = \(i) the j = \(j++)")
}

and

var j: Int = 0
for var i: Int = 0; i < 4; ++i {
    print("the i = \(i) the j = \(++j)")
}
Dan Loughney
  • 4,647
  • 3
  • 25
  • 40