以下是我正在处理的代码的过度简化版本。我想检查一个索引是否在有效的边界内,如果在给定索引的数组中,在一个if语句中有一个对象。
int main(){
int* anArray[5]; // in the code there's either an object here or a nullptr
int anIndex = 2; // something that I get from the depths of my code
// int* <- typename not allowed
// elem <- indentifier is undefined
if(anIndex < 5 && int* elem = anArray[anIndex]){
// use elem here
}
return 0;
}
我可以使用两个if语句检查索引,然后检查对象,但过了一段时间,if语句到处都有,我想避免这种情况。我做错了什么?
编辑:问题不在于索引,问题是如果我检查和,那么我想得到一个指针,我得到上面提到的错误if-statement答案 0 :(得分:5)
使用Conditional (or Ternary) Operator(?
)。在运算符的条件表达式中评估索引是否在bouds中。如果表达式计算为true
,则可以直接访问该数组。 false
案例的表达式为nullptr
:
int* anArray[5];
int anIndex = 2;
if ( int* elem = anIndex >= 0 && anIndex < 5 ? anArray[anIndex] : nullptr ){
// use elem here
}
答案 1 :(得分:2)
这样做;
if(anIndex < 5 && anArray[anIndex]){
int* elem = anArray[anIndex]
}
如果你需要,你可能想检查anIndex是否也是> = 0。
答案 2 :(得分:0)
int anIndex = 2; // something that i get from the depths of my code
if(anIndex < 5 && int* elem = anArray[anIndex]){
// use elem here
}
在理论上,anIndex可能是负面的,因此需要额外检查:
int *elem = NULL;
if(anIndex >= 0 && anIndex < 5 && (elem = anArray[anIndex])){
// use elem here
// will only get here if elem is not NULL
}
答案 3 :(得分:0)
如果条件不满足,我会将其反转退出,以便在添加更多条件时更容易理解:
FileObserver
考虑一下通过调试器来找出边缘情况时的容易程度。