在同一if语句中检查nullptr和有效索引

val*_*val 2 c++ pointers if-statement

这是我正在处理的代码的过度简化版本.我想检查一个索引是否在有效的边界内,如果在给定索引的数组中,在一个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;
}
Run Code Online (Sandbox Code Playgroud)

我可以使用两个if语句检查索引,然后检查对象,但过了一段时间,if语句到处都有,我想避免这种情况.我究竟做错了什么?

编辑:问题不在索引,问题是,如果我检查一些东西,然后我想得到一个指针,我得到上面提到的错误if语句

Rab*_*d76 5

使用条件(或三元)运算符(?).在运算符的条件表达式中评估索引是否在bouds中.如果对表达式求值true,则可以直接访问该数组.false案件的表达方式是nullptr:

int* anArray[5];
int anIndex = 2;

if ( int* elem = anIndex >= 0 && anIndex < 5 ? anArray[anIndex] : nullptr ){
    // use elem here
}
Run Code Online (Sandbox Code Playgroud)