painkiller
painkiller

Reputation: 149

How does 'for' work when all of its "parts" are 'i++'?

I've used Code::Blocks to find the result, and it gives me 2 at the end, where i + j = 1 + 1.

#include <stdio.h>

int main(void) {
    int i = -1, j = 1;

    for(i++; i++; i++)
        j++;

    printf("%d",i + j);
    return 0;
}

How does i get to be 1, and why was j not incremented?

Upvotes: 3

Views: 117

Answers (3)

S.S. Anne
S.S. Anne

Reputation: 15586

Here's the order in which it executes:

  1. i is -1 and j is 1

  2. i is incremented (after which i == 0)

  3. The loop checks if i != 0. Since i is 0 at this point, the contents of the loop are skipped.

  4. i is incremented again (after which i == 1)

  5. The code prints i + j, which is 2 because j is unchanged and i is 1.

Here's a program with a while loop that does the same thing as the program in your question:

int main(void) {
    int i = -1, j = 1;
    i++;
    while(i++)
    {
        j++;
        i++;
    }
    printf("%d",i + j);
    return 0;
}

To directly answer your question:

  • i is 1 afterwards because it is incremented twice from an original value of -1.

  • j is not incremented because the contents of the loop are skipped.

Upvotes: 3

Naveen Jain
Naveen Jain

Reputation: 1072

Let me first explain how for loop execution happens:

  1. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

  2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.

Increment operator: value of i increments after execution if it is i++

Explanation of your code:

 for(i++; i++; i++)  
  1. At init step i++ been executed but i will be still 0 until it get to condition step of for loop.

  2. i becomes zero it means condition is false but at same time one more i++ already executed.

  3. As condition is false for loop statement will never be executed and value of i will be 1 and value of j remains 1.

Upvotes: 1

Acorn
Acorn

Reputation: 26166

You start with i == -1, j == 1.

Then you run the first i++, which will make i == 0. The result (which is the original value of i) is unused.

Then you test for the first time in i++. Since i is already 0, the test is false, so the for loop will quit. Now the post-increment runs, which makes it i == 1, and the loop exits.

Note how j++; was never reached!

To see it more clearly, you can think about the for loop in the following equivalent way:

i++;           // init statement
while (i++) {  // condition
    j++;       // body of the for loop
    i++;       // iteration expression
}

Upvotes: 6

Related Questions