0

I vaguely recall that GCC had an extension letting you write something like:

    total += { if ( b == answerb ) {
              printf( "b = %d (correct)\n", b );
              return 1;
          } else {
              printf( "b = %d (incorrect, answer was %d)\n", b, answerb );
              return 0;
        };

The code inside the outer braces would run, with the return value being assigned to total.

This existed (if it indeed existed) with the main intent that you could write the code to the right of that = in a macro that was similar to an inline function but also letting you do preprocessor tricks with the symbols such as using # and ## on the macro arguments to construct variable names and strings from the macro parameters, which cannot be done with inline functions:

#define SCORE( test, correct ) \
    { if ( test == correct ) { \
              printf( #test "= %d (correct)\n", test ); \
              return 1; \
          } else { \
              printf( #test " = %d (incorrect, answer was %d)\n", test, correct ); \
              return 0; \
        };
total = 0;
total += SCORE( a, answera );
total += SCORE( b, answerb );

Does this actually exist? If so, what is it called, so I can research it further? How does it work? And was it made part of the C/C++ standards?

Swiss Frank
  • 1,985
  • 15
  • 33

1 Answers1

1

What about the following approach?

#define CHECK_ADD_SCORE( test, correct, total ) \
{ if ( test == correct ) { \
          printf( #test "= %d (correct)\n", test ); \
          total += 1; \
      } else { \
          printf( #test " = %d (incorrect, answer was %d)\n", test, correct ); \
};
total = 0;
CHECK_ADD_SCORE( a, answera, total );
CHECK_ADD_SCORE( b, answerb, total );
VolAnd
  • 6,367
  • 3
  • 25
  • 43
  • thx, achieves the aim of my example quite cleanly, but to be clear I was looking not for a clean or portable solution, but rather the NAME of a feature that allowed "return" statements like that.... – Swiss Frank Aug 04 '21 at 13:05
  • @SwissFrank for such cases just use function, that returns value. `return 1;` and `return 0;` work for functions of type `int`. Do not waste time on macros – VolAnd Aug 14 '21 at 19:37