gab*_*ous 1 c return function void
我有一个double函数,通常返回变量的新值,但有时我不想更改变量,我想通过返回一个特殊值来表示,例如void.那可能吗?
例如:
double GetNewValue(int feature) {
switch( feature ) {
case TYPE1:
return void; // or maybe use return; here?
case TYPE2:
return 2.343;
default:
return featureDefaultValue;
}
}
Run Code Online (Sandbox Code Playgroud)
PS:我知道我可以使用NaN,但我已经将它用作具有其他含义的有效值(还没有数字可用).
/编辑:谢谢大家的答案,这3个答案都适用于我的问题,并且都同样有效.我现在正在努力选择我将要使用哪一个(我会接受的那个,但我希望我能接受它们!).
在这种情况下,您需要从函数返回两个东西,而不是一个.一种常见的方法是使用指向返回值的指针,并返回yes/no标志以指示实际的有效性double:
int GetNewValue(double *res, int feature) {
switch( feature ) {
case TYPE1:
return 0; // no change to res
case TYPE2:
*res = 2.343;
return 1;
default:
*res = featureDefaultValue;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
现在不是这样做的
double res = GetNewValue(myFeature);
Run Code Online (Sandbox Code Playgroud)
您的函数的用户需要这样做:
double res;
if (GetNewValue(&res, myFeature)) {
// use res here - it's valid
} else {
// do not use res here - it's not been set
}
Run Code Online (Sandbox Code Playgroud)