C++ 并非所有控制路径都返回值

C++ 并非所有控制路径都返回值,c++,visual-studio,c++11,C++,Visual Studio,C++11,为什么Visual Studio使用以下代码向我显示该错误: int func( int a ) { if ( a < 0 ) return -a & 3; else if ( a > 0 ) return a | 8; else if ( a == 0 ) return 10; } int func(int a) { if(a0),则为else 返回a | 8; 如果(a==0),则为else

为什么Visual Studio使用以下代码向我显示该错误:

    int func( int a )
{
    if ( a < 0 )
        return -a & 3;
    else if ( a > 0 )
        return a | 8;
    else if ( a == 0 )
        return 10;
}
int func(int a)
{
if(a<0)
回报-a&3;
如果(a>0),则为else
返回a | 8;
如果(a==0),则为else
返回10;
}

编译器似乎不够聪明。:)

尝试按以下方式更改函数体

if ( a < 0 )
    return -a & 3;
else if ( a > 0 )
    return a | 8;
else 
    return 10;
if(a<0)
回报-a&3;
如果(a>0),则为else
返回a | 8;
其他的
返回10;
您也可以在else之后放置评论,因为@buc

if ( a < 0 )
    return -a & 3;
else if ( a > 0 )
    return a | 8;
else /* a == 0 */ 
    return 10;
if(a<0)
回报-a&3;
如果(a>0),则为else
返回a | 8;
else/*a==0*/
返回10;

编译器不够聪明,无法意识到必须命中三个案例中的一个。更好的书写方式是:

int func( int a )
{
    if ( a < 0 )
    {
        return -a & 3;
    }

    if ( a > 0 )
    {
        return a | 8;
    }

    // a must be 0
    return 10;
}
int func(int a)
{
if(a<0)
{
回报-a&3;
}
如果(a>0)
{
返回a | 8;
}
//a必须是0
返回10;
}

在函数作用域结束之前,您缺少一条
return
语句。关于这个错误消息,实际上有什么不清楚的地方?我通常还会对最后一个else子句中的条件进行注释,这样以后更容易理解代码:
else/*a==0*/
@buc我同意你的看法。