I recently came accross some C++ code like the following:
if(test_1)
if(test_2)
{
// Do stuff
}
else
exit(0);
This is ambiguous, since the compiler could see this as:
if(test_1)
{
if(test_2)
{
}
else
{
}
}
or as:
if(test_1)
{
if(test_2)
{
}
}
else
{
}
Is the behaviour of this code defined according to any standard (C, C++)? I saw this code in a C++ program on VC++, which seems to prefered the first solution.
Yes, it is defined. In C (and all similar languages as I know), the “dangling else” binds to the last free if, therefore this interpretation
is correct.