【问题标题】:C, error: control reaches end of non-void function [-Werror,-Wreturn-type]C、错误:控制到达非空函数结束[-Werror,-Wreturn-type]
【发布时间】:2013-10-03 02:38:24
【问题描述】:
struct quad {
int a;
int b;
int c;
}

int f(const int a, const int b, const int c, const int x){
  const int l = a*x*x + b*x + c;
  return l;
}

int safe_quad_eval(const struct quad q, const int x){
  (f(q.a,q.b,q.c,x)>INT_MAX)||(f(q.a,q.b,q.c,x)<(-INT_MAX)) ? INT_MIN : f(q.a,q.b,q.c,x);
}

我不确定这个错误是什么意思?以及如何解决?

【问题讨论】:

    标签: c


    【解决方案1】:

    函数int safe_quad_eval(...)没有返回值。

    你需要返回一个 int。

    也许你想要

    int safe_quad_eval(const struct quad q, const int x){
        return (f(q.a,q.b,q.c,x)>INT_MAX)||(f(q.a,q.b,q.c,x)<(-INT_MAX)) ? INT_MIN : f       (q.a,q.b,q.c,x);
        }
    

    【讨论】:

      【解决方案2】:

      safe_quad_eval() 没有返回语句。应该是return (f(q.a,q.b...

      【讨论】:

        【解决方案3】:

        如果我们查看gcc 手册的Warning Options 部分,我们会看到-Wreturn-type 的以下内容:

        每当函数定义的返回类型默认为 int 时都会发出警告。还警告返回类型不是 void 的函数中没有返回值的任何 return 语句(从函数体的末尾脱落被认为返回没有值),以及返回类型的函数中带有表达式的 return 语句是无效的。

        在这种情况下,safe_quad_eval 被声明为返回 int,但是你在没有 return 语句的情况下退出了函数的末尾。如果您尝试按照 C99 草案标准部分 6.9.1 函数定义 段落 12 使用此类函数的返回值,这可能会导致未定义的行为:

        如果到达终止函数的 },并且调用者使用了函数调用的值,则行为未定义。

        因此,您可能应该将函数更改为 return 一个值。

        为了完整起见,-Werror 将导致编译器将警告转化为错误,来自上面链接的手册:

        -错误

        将所有警告变成错误。

        【讨论】:

          【解决方案4】:

          函数safe_quad_eval 开头的int 表示它应该返回一个整数值。但是,正如您所写,它实际上并没有返回任何内容(其中没有 return 语句)。

          要解决此问题,请在其正文开头添加 return

          int safe_quad_eval(const struct quad q, const int x){
              return (f(q.a,q.b,q.c,x)>INT_MAX)||(f(q.a,q.b,q.c,x)<(-INT_MAX)) ? INT_MIN : f(q.a,q.b,q.c,x);
          }
          

          【讨论】:

            【解决方案5】:

            我假设您想返回 safe_quad_eval 中的值,因为返回类型被声明为 int,但您忘记了 return 语句。添加return 应该会阻止编译器抱怨。

            int safe_quad_eval(const struct quad q, const int x){
              return (f(q.a,q.b,q.c,x)>INT_MAX)||(f(q.a,q.b,q.c,x)<(-INT_MAX)) ? INT_MIN : f(q.a,q.b,q.c,x);
            }
            

            error: control reaches end of non-void function 意味着一个函数被声明为非 void(safe_quad_eval 在这种情况下期待一个 int 返回值),但你没有从它返回一个值。添加int 返回值可以更正错误。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-12-04
              • 1970-01-01
              • 2016-08-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多