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
?