【问题标题】:compiler error: control reaches end of non-void function [duplicate]编译器错误:控制到达非无效函数的结尾[重复]
【发布时间】:2016-12-22 05:33:45
【问题描述】:

我有这段代码,编译器给了我下一个错误:

functions.c:12:1: 警告:控制到达非空函数的末尾 [-Wreturn 类型] }

代码:

#include <stdlib.h>
#include <time.h>

int myrand(){

    srand(time(NULL));
    int r = rand()%2;

}

此函数是从此处的另一个 .c 文件调用的:

printf("%d here \n", myrand());

【问题讨论】:

  • int myrand(){ ... } 是一个返回 int 的函数。编译器期待 return 语句,比如 return r; 可能
  • 该函数应该返回一个int 值。
  • 恭喜。您对这些披露有疑问吗?

标签: c compiler-errors


【解决方案1】:

经过大量研究和阅读手册后,我发现了错误,结果控制到达了非空函数的末尾。

int myrand(){

    srand(time(NULL));
    int r = rand()%2;
    return r; // add this
}

【讨论】:

    【解决方案2】:

    添加返回语句。

    int myrand(){
    
        srand(time(NULL));
        int r = rand()%2;
        return r;
    }
    

    没有它,您打印的“随机”值不会来自rand(),而是来自省略返回语句的未定义行为。 [嗯,从技术上讲,根据架构,rand 的返回值可以在寄存器中传播]

    虽然 标准可能允许在不要求出现硬错误的情况下省略它,但这仍然是不明智的。

    【讨论】:

    • 非常感谢,刚刚自己看到这个错误)
    猜你喜欢
    • 2016-05-07
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多