[英]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++)
说:
i
to zero.i
初始化为零。i < 10
is true.i < 10
是否为真。 If it is, execute the body of the loop.i
and go to step 2.i
和 go 递增到第 2 步。 Therefore, the loop continues executing until i < 10
is false .因此,循环继续执行直到
i < 10
为false 。
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.