在 C 中使用 for 循环测试函数的 return 值

Using a for-loop in C to test the return value of a function

我对编码尤其是 C 还很陌生,所以我决定参加 CS50 课程作为对这门语言的介绍。我刚看完关于 C 的第一堂课,为了测试我对这门学科的知识,我尝试编写一个简短的小程序。此外,我正在使用课程的库来实现 get_int() 功能。

目标是测试用户的输入并检查它是否小于或等于十。如果匹配参数,程序应该打印 "Success!" 消息并退出;否则,它应该再次要求输入。如果输入值超过 10,程序会按预期响应,但如果您输入的值小于或等于 10,它最终会在实际退出前再次要求您输入一次。我认为这可能与 "for" 循环有关,但我就是想不通。

我的代码:

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>

int check_for_value();

int main()
{
    for(check_for_value(); check_for_value() != 1;  check_for_value())
    {
        printf("Failed!\n");
    }
    exit(0);
}

int check_for_value()
{
    int i = get_int("Your value: \n");

    if(i <= 10)
    {
        printf("Success!\n");
        return 1;
    }    
    else
    {
        printf("Try again!\n");
        return 0;
    }
}

for 循环看起来非常简单

for ( ; !check_for_value(); )
{
    printf("Failed!\n");
}

在这种情况下,最好使用 while 循环

while ( !check_for_value() )
{
    printf("Failed!\n");
}

至于你的for循环

for(check_for_value(); check_for_value() != 1;  check_for_value())
    ^^^^^^^^^^^^^^^^^                           ^^^^^^^^^^^^^^^^^

那么函数的下划线调用没有测试。

还要记住这样定义一个for循环

for(int ret = check_for_value(); ret != 1; ret = check_for_value()) {
    printf("Failed\n");
} 

是一种非常糟糕的编程风格。有函数调用的冗余记录。循环体中没有使用中间变量 ret。所以它的声明也是多余的。永远不要使用这样的编程风格。

注意根据C标准,不带参数的函数main应该声明为

int main( void )

和声明

exit( 0 );

是多余的。

这并不完全符合您的想法。在您的 for 循环中,每次您编写 check_for_value() 时,它都会调用该函数。所以它会在第一次调用它并且 return 值无关紧要。它将在中间语句中再次调用它,然后该值将很重要,因为您将输出与不等于 1 进行比较。然后它将再次调用第三条语句中的函数,这再次无关紧要。通常对于这样的事情,您会改用 while 循环。下面是一个例子:

int ret = check_for_value();
while(ret != 1) {
    printf("Failed\n");
    ret = check_for_value();
}

printf("Success\n");

从技术上讲,for 循环也可以按如下方式工作:

for(int ret = check_for_value(); ret != 1; ret = check_for_value()) {
    printf("Failed\n");
}