0

Is the following a safe code?

int main()
{
  std::vector<int> v = buildVector();
  if (v.size() > 2 && v[1]==2)
  {
     doThis();  
  } else
  {
     doThat();  
  }
}

or should do I rather do

int main()
{
  std::vector<int> v = buildVector();
  if (v.size() > 2)
  {
     if (v[1] == 2)
     {
        doThis();
     } else
     {
        doThat();
     }
  } else
  {
     doThat();
  }
}

My fear is that it would try to evaluate v[1] == 2 before v.size() > 2 and yield to a segmentation fault or something. How about a similar situation using logical OR?

Will C++ always evaluate the expressions in a if condition in the order provided and stop as soon as it has enough information to know if it is true or false?

Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • https://en.wikipedia.org/wiki/Short-circuit_evaluation I suggest you read a book on C++ first. – Henri Menke Mar 11 '18 at 00:03
  • It is a duplicate indeed. From what I get, the first code is safe. Thank you. Thanks also for the link to wiki > short-circuit evaluation. – Remi.b Mar 11 '18 at 00:06

0 Answers0