You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50课程C语言编译错误:非void函数未在所有控制路径返回值

CS50 Caesar作业编译错误修正

我正在学习CS50课程的C语言部分,完成第二周的Caesar编程作业。作为纯新手,我的代码可能存在诸多问题。目前我尝试编写一个函数,用于检查用户是否正确使用命令行输入,且输入仅包含整数。以下是我的代码:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

bool only_digits(string s);

int main(int argc, string argv[])
{
    if (argc == 2 & only_digits > 0)
    {
        printf("test\n");
    }
    else
    {
        printf("usage: ./caesar key\n");
    }
}

bool only_digits(string s)
{
    for (int i = 0, n = strlen(s); i < n; i++)
        {
            if (isdigit(i))
            {
                return 0;
            }

            else
            {
                return 1;
            }
        }
}

编译时出现如下错误:

caesar/ $ make caesar 
caesar.c:34:1: error: non-void function does not return a value in all control paths [-Werror,-Wreturn-type]
}
^
1 error generated.
make: *** [: caesar] Error 1

错误分析与修正方案

1. 编译错误的直接原因

only_digits函数存在路径未返回值的问题:如果传入空字符串(循环未执行),函数没有返回值,违反了C语言非void函数必须在所有执行路径返回值的要求。此外代码还有多处逻辑错误:

2. main函数中的错误

  • 逻辑运算符误用:应使用逻辑与&&而非按位与&
  • 函数调用错误:未传入参数调用only_digits,需要传入命令行参数argv[1],并判断函数返回的布尔值
    修正后的判断条件:
if (argc == 2 && only_digits(argv[1]))

3. only_digits函数中的逻辑错误

  • 参数传递错误:isdigit应检查字符串的字符s[i],而非循环索引i
  • 逻辑颠倒且提前返回:当前代码仅检查第一个字符就返回,正确逻辑是遇到非数字字符立即返回false,遍历完所有字符后返回true
    修正后的函数:
bool only_digits(string s)
{
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        if (!isdigit(s[i])) // 遇到非数字字符,返回false
        {
            return false;
        }
    }
    // 所有字符都是数字,返回true
    return true;
}

修正后的完整代码

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

bool only_digits(string s);

int main(int argc, string argv[])
{
    if (argc == 2 && only_digits(argv[1]))
    {
        printf("test\n");
    }
    else
    {
        printf("usage: ./caesar key\n");
    }
}

bool only_digits(string s)
{
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        if (!isdigit(s[i]))
        {
            return false;
        }
    }
    return true;
}

内容的提问来源于stack exchange,提问作者dariocodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:24:17