Date: Thu, 3 Jul 2025 10:55:17 +0100
I use "if else ladders" a fair bit in my code. Here's code that I'm
looking at right now:
if ( 7u == p.size() ) // P1234R0
{
// fall through
}
else if ( isdigit(p[7]) ) // length is >= 8
{
rev *= 10u;
rev += (p[7]-'0');
if ( (p.size() > 8u) && ('\0' != p[8]) && ('.' !=
p[8]) ) break; // P1234R15
// fall through
}
else if ( ('\0' == p[7]) || ('.' == p[7]) ) // length is >= 8
{
// fall through
}
else // length is >= 8
{
break;
}
Sometimes in an "if else ladder", you want to enter one of the code
blocks, but if something goes wrong in that code block, you want to
jump back out of it and continue down the ladder. So maybe "goto
else;" could be used for this? The above code could become:
unsigned index = 7u;
if ( 7u == p.size() ) // P1234R0
{
// fall through
}
else if ( isdigit(p[7]) ) // length is >= 8
{
rev *= 10u;
rev += (p[7]-'0');
if ( p.size() > 8u )
{
++index;
goto else;
}
// fall through
}
else if ( ('\0' == p[index]) || ('.' == p[index]) )
// length >= 8u
{
// fall through
}
else // length >= 8u
{
break;
}
This would greatly simplify some of the most complicated "if else ladders".
And I actually think we should have something similar for 'catch'
ladders, so that we can do:
catch( std::exception const &e )
{
cout << e.what() << endl;
goto catch; // continues down the ladder
}
catch(...)
{
cout << "An exception was thrown\n";
}
So if an exception of type "std::exception" is thrown, it enters the
first catch handler, and then enters the second catch handler also.
looking at right now:
if ( 7u == p.size() ) // P1234R0
{
// fall through
}
else if ( isdigit(p[7]) ) // length is >= 8
{
rev *= 10u;
rev += (p[7]-'0');
if ( (p.size() > 8u) && ('\0' != p[8]) && ('.' !=
p[8]) ) break; // P1234R15
// fall through
}
else if ( ('\0' == p[7]) || ('.' == p[7]) ) // length is >= 8
{
// fall through
}
else // length is >= 8
{
break;
}
Sometimes in an "if else ladder", you want to enter one of the code
blocks, but if something goes wrong in that code block, you want to
jump back out of it and continue down the ladder. So maybe "goto
else;" could be used for this? The above code could become:
unsigned index = 7u;
if ( 7u == p.size() ) // P1234R0
{
// fall through
}
else if ( isdigit(p[7]) ) // length is >= 8
{
rev *= 10u;
rev += (p[7]-'0');
if ( p.size() > 8u )
{
++index;
goto else;
}
// fall through
}
else if ( ('\0' == p[index]) || ('.' == p[index]) )
// length >= 8u
{
// fall through
}
else // length >= 8u
{
break;
}
This would greatly simplify some of the most complicated "if else ladders".
And I actually think we should have something similar for 'catch'
ladders, so that we can do:
catch( std::exception const &e )
{
cout << e.what() << endl;
goto catch; // continues down the ladder
}
catch(...)
{
cout << "An exception was thrown\n";
}
So if an exception of type "std::exception" is thrown, it enters the
first catch handler, and then enters the second catch handler also.
Received on 2025-07-03 09:55:26