简体   繁体   English

C++ 中布尔函数的默认返回值是多少?

[英]What is the default return value of a Boolean function in C++?

What could be the return value of a boolean function in C++ if I do not return something?如果我不返回某些东西,C++ 中布尔函数的返回值是什么? And what could be the return value if I just return a true value and not the false one?如果我只返回一个真值而不是假值,那么返回值是什么? Here is my code:这是我的代码:

bool f(int a)
{
//    return value?
}

bool f(int a)
{
    if(a%2) return true;
//    return value here?
}

The return type is the one you define in the function prototype.返回类型是您在函数原型中定义的类型。 Note that there is no default return value for functions in C++ (except for special function main ).请注意,C++ 中的函数没有默认返回值(特殊函数main除外)。 A function that is supposed to return a value must return a value in all its code paths.应该返回值的函数必须在其所有代码路径中返回一个值。 Otherwise you yield undefined behaviour.否则你会产生未定义的行为。 Cf, for example, this online C++ working draft :例如,参见这个在线C++ 工作草案

9.6.3 The return statement 9.6.3 返回语句

... ...

Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand.从构造函数、析构函数或具有 cv void 返回类型的函数的末尾流出等价于没有操作数的返回。 Otherwise, flowing off the end of a function other than main (6.8.3.1) results in undefined behavior.否则,从 main (6.8.3.1) 以外的函数的末尾流出会导致未定义的行为。

The behaviour on calling a non- void function (other than main ) where program control reaches a branch that does not have an explicit return value is undefined .在程序控制到达没有显式return值的分支时调用非void函数( main除外)的行为是未定义的

(Note that this is a stronger condition than in C where the behaviour is undefined only if you attempt to use the function return value.) (请注意,这是一个比 C 中更强的条件,只有当您尝试使用函数返回值时,行为才未定义。)

In C++, you can use auto to get the compiler to work out the return type for you:在 C++ 中,您可以使用auto来让编译器为您计算出返回类型:

auto foo(int n)
{
    if (n >= 0){
        return true;
    } else {
        return false;
    }
}

but the type of foo is still static in the sense that it is known at compile time.但是foo的类型在编译时已知的意义上仍然是静态的。 This approach is particularly useful when working with templates.这种方法在使用模板时特别有用。 It is not designed to allow you to be sloppy with your types.它不是为了让你对你的类型马虎。

you can not do that if you write a function that supposes to return something and you return nothing you get and error.如果您编写了一个假设返回某些内容的函数,而您没有返回任何内容并出错,那么您就不能这样做。 so use void or return something.所以使用 void 或返回一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM