Home > other >  Can someone please explain why this C function is returning the value of 10?
Can someone please explain why this C function is returning the value of 10?

Time:10-08

Beginner question on C function here so please bear with me...

#include <stdio.h>
 #include <stdlib.h>
int some_function(void);

int result;
result = some_function();
printf("%d", result);

return 0;
}

int some_function(void)
{
    int i;
    for (i = 0; i < 10; i  )
    {
        // printf("%d", i);
    }

    return (i);    
}

I commented out the result of running the for loop which is all integers from 0 to 9.

I can not clearly understand why the final result of local int i is increased once more to finally provide a return of 10 out of int some_function(void).

Thank you so much for any help.

CodePudding user response:

for (i = 0; i < 10; i ) says:

  1. Initialize i to zero.
  2. Test whether i < 10 is true. If it is, execute the body of the loop. If it is not, exit the loop.
  3. Increment i and go to step 2.

Therefore, the loop continues executing until i < 10 is false.

When i is nine, i < 10 is true, and the loop does not exit. When i is ten, then i < 10 is false, and the loop exits.

Therefore, when the loop exits, i is ten.

CodePudding user response:

for (i = 0; i < 10; i  ) {
    ...
}

is equivalent to

i = 0
while (i < 10) {
    ...
    i  ;
}

When i is 9, the loop body is executed, then i is incremented (and its value is now 10), then the test of the while loop is executed once more, and the loop exits, with i still having the value 10.

  • Related