不打印程序的返回值时,计算字符串长度不正确

Pau*_*use 5 c arrays string loops

长度是假设当通过弦时返回计数器走了多远.但是,它只会在预先打印时返回正确的值.如果我注释掉printf它会返回0.有没有人对此有解释?

#include<stdio.h>
#include<string.h>
#define MAX 100

int length(char *s) {
    int i;
    for (i = 0; s[i] != '\0'; ++i)
        printf("%d ", i);           //<-- here
    return i;
}

int main() 
{
    char s[MAX];
    fgets(s, (char)sizeof(s), stdin);
    s[strcspn(s, "\n")]='\0';
    printf("Length: %d\n", length(s));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 7

问题是,如果你注释掉printf()在声明length()功能,return声明将成为循环体的一部分,从呼叫的第一个迭代的回报,你会得到的,那么价值i,这仅仅是对的入账价值循环,0.

for (i = 0; s[i] != '\0'; ++i)
    //printf("%d ", i);           //<-- here
return i;                         // without brace-enfoced scope, this is the loop body.
Run Code Online (Sandbox Code Playgroud)

是相同的

for (i = 0; s[i] != '\0'; ++i)
return i;                                
Run Code Online (Sandbox Code Playgroud)

你需要的是完成执行的循环,点击退出条件,然后执行return最新值为的语句i.

因此,为了避免这个问题,您可以通过类似的方式强制执行循环的空执行

for (i = 0; s[i] != '\0'; ++i) ;   // notice the ; here, ends the scope.
return i; 
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好(对于读者)

for (int i = 0; i < 10; i++) 
    {/*nothing here*/}       //indicates empty loop body
return i;
Run Code Online (Sandbox Code Playgroud)

注意:作为一种替代方法,为了增强可读性,for您可以使用while循环,而不是构造

while (s[i] != '\0') 
{
    i++;                     //increment statement is explicit.
}
Run Code Online (Sandbox Code Playgroud)


For*_*Bru 5

在这样的循环中:

for (...)
    statement1;
statement2;
Run Code Online (Sandbox Code Playgroud)

statement1将是循环中唯一执行的事情.当您注释掉printf调用时,return i;在第一次迭代时执行,立即返回零.

但是,请注意,statement1可以为空,因此,要运行没有正文的循环,请执行以下操作:

for (...)
    ; // yes, a hanging semicolon

// or like this:
for (...);
Run Code Online (Sandbox Code Playgroud)