0

The following code is simple, What I want to know is the execution time for ++counter. I know for a for loop, count<5 is the first condition to check,but then for the execution time of ++counter I'm not so sure. line 1, 2 or 3, which is the place to execute increment?

#include <stdio.h>

int main()
{
int counter;
/* counter for loop */

for (counter = 0; counter < 5; ++counter) {  // 1
printf("x %d\n", counter+1);  // 2
} //3
return (0);
}

And the result is

x 1    
x 2    
x 3    
x 4    
x 5    
tshepang
  • 12,111
  • 21
  • 91
  • 136
web rocker
  • 217
  • 1
  • 3
  • 10
  • 2
    The result you shown is not compatible with the program you posted. – pmg Apr 15 '14 at 08:52
  • And the results you got together with the info available on that increment operator could easilly indicate you what happens when. I don't understand your question. – Laurent S. Apr 15 '14 at 08:53

4 Answers4

2

I am not getting the X 0 for ++counter Ideone Output

and the position of ++counter wont matter for your change in X value as instrumentation for the for loop is done is after the execution of one cycle(assuming the expression is true)

Check this link fo rtutorial on for loop Loops

KARTHIK BHAT
  • 1,410
  • 13
  • 23
  • My fault. I tried different version and got several results and mixed them up. It is always 1 for the first element. and Thank you for your Loop tutorial. that's clear! – web rocker Apr 15 '14 at 09:08
0

++counter is executed after printf("x %d\n", counter+1); in each iteration.

nni6
  • 990
  • 6
  • 13
0

To boil it down, a for loop can be transformed into a while loop like such:

for (initialization,condition,iteration)
{
    //code
}

initialization
while(condition)
{ 
    //code
    iteration
}

so i++ or ++i are executed after the loop runs through, and then the condition is checked for the loop to be run again.

GriffinG
  • 662
  • 4
  • 13
0

You can interpret the following for-loop

for (variable initialization; ending condition; variable update) {
    // code
}

as a shortened while loop

variable initialization
while(ending condition) {
    // code
    variable update
}

thus your counter++ or ++counter is executed after the statements in the loop.

To be fair, it doesn't matter which increment, either post- or prefix you want to use. But performance wise, prefix is a bit faster then postfix in some circumstances. IF you are interested in why, you can refer to this explanation.

KarelG
  • 5,176
  • 4
  • 33
  • 49