简体   繁体   English

有人可以解释为什么这个 C function 返回值 10 吗?

[英]Can someone please explain why this C function is returning the value of 10?

Beginner question on C function here so please bear with me...关于 C function 的初学者问题请耐心等待...

#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.我注释掉了运行 for 循环的结果,它是从 0 到 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).我无法清楚地理解为什么本地 int i 的最终结果会再次增加以最终提供 10 out of int some_function(void) 的返回值。

Thank you so much for any help.非常感谢您的帮助。

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

  1. Initialize i to zero.i初始化为零。
  2. Test whether i < 10 is true.测试i < 10是否为真。 If it is, execute the body of the loop.如果是,则执行循环体。 If it is not, exit the loop.如果不是,则退出循环。
  3. Increment i and go to step 2.i和 go 递增到第 2 步。

Therefore, the loop continues executing until i < 10 is false .因此,循环继续执行直到i < 10false

When i is nine, i < 10 is true, and the loop does not exit.i为 9 时, i < 10为真,循环不退出。 When i is ten, then i < 10 is false, and the loop exits.i为 10 时, i < 10为假,循环退出。

Therefore, when the loop exits, i is ten.因此,当循环退出时, i为 10。

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.i为 9 时,执行循环体,然后i递增(现在它的值为 10),然后再次执行 while 循环的测试,循环退出, i的值仍然为 10。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM