警告:“并非所有控制路径都返回值".C ++ [英] Warning : "Not all control paths return a value" c++

查看:87
本文介绍了警告:“并非所有控制路径都返回值".C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的小功能,我不理解此警告:

I don't understand this warning for my little function:

int Fct_name (int nb1, int * nb2) 
{
    switch (Dest)
    { 
    Case 1 : 
        return Fct_1(nb1,nb2);
    Case 2 :
        return -1;
    }
}

有人可以帮助我吗?

推荐答案

这是因为,正如警告所言,并非所有代码路径都返回一个值,而该函数具有一个独特的返回类型,该类型告诉编译器嘿,我要退还一些东西."但是如果 Dest 不是1或2,则实际上不执行此操作.

It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if Dest is anything other than 1 or 2.

您评论了:

目标只能是1或2(这是一个枚举)

Dest can only be 1 or 2 (it's an enum)

是的,但是只有您知道,编译器不知道,并且不会接受您的要求.它只能看到代码的静态属性,无法预测运行时的运行方式,因此不会接受您的代码.众所周知,目标可以通过外部代码等来更改.

Yes okay but only you know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows Dest can be changed by an external piece of code etc etc.

您应该添加某种默认值:

You should add some sort of default value:

int Fct_name (int nb1, int * nb2) 
{
   switch (Dest)
   { 
    case 1 : 
         return Fct_1(nb1,nb2);
    case 2 :
         return -1;
    }
    return 0;
}

这篇关于警告:“并非所有控制路径都返回值".C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆