I like from the C++ unit test framework Catch2 its sections -- much more than the xUnit test fixtures. Therefore I wrote me some macros which mimic the Catch2 sections.
This is the first macro heavy code I wrote, so I am mostly interested whether the macros do what they should do, or not.
#include <utility>
#define TOKENPASTE_HELPER(x, y) x ## y
#define TOKENPASTE(x, y) TOKENPASTE_HELPER(x, y)
#define CASE( name ) \
if ( int executed_section = 0, first_run = 0; true ) \
while ( std::exchange(executed_section, 0) || first_run++ == 0 )
#define SECTION( name ) \
static int TOKENPASTE(counter_done_, __LINE__) = 0; \
goto TOKENPASTE(section_start_, __LINE__); \
TOKENPASTE(section_end_, __LINE__): \
continue; \
TOKENPASTE(section_start_, __LINE__): \
while ( true ) \
if ( TOKENPASTE(counter_done_, __LINE__) == 2 ) { \
break; \
} else if( TOKENPASTE(counter_done_, __LINE__) == 1 ) { \
TOKENPASTE(counter_done_, __LINE__) = 2; \
goto TOKENPASTE(section_end_, __LINE__); \
} else if ( TOKENPASTE(counter_done_, __LINE__) = 1, executed_section=1; true )
They are used like this:
#include <cassert>
int main() {
CASE( i_test ) {
int i = 0;
SECTION( i==1 ) {
++i;
assert( i == 1 );
}
SECTION( i == 0 ) {
assert( i == 0 );
}
}
CASE( ii_test ) {
int i = 10;
SECTION() {
assert( i==10 );
}
}
}
gcc -Eor equivalent. \$\endgroup\$