jeudi 7 janvier 2016

Check for nullptr and valid index in the same if statement

Here is an oversimplified version of a code iam working on. I want to check if an index is in valid bounds and if in an array at the given index there's an object in one if statement.

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;
}

I can use two if statements to check the index and then check for the object, but after a while there are if statements everywhere, and i'd like to avoid that. What am i doing wrong?

Aucun commentaire:

Enregistrer un commentaire