0

我隐约记得 GCC 有一个扩展,可以让你编写如下内容:

    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;
        };

外部大括号内的代码将运行,返回值被分配给total.

这存在(如果确实存在的话)的主要目的是您可以=在类似于内联函数的宏中编写代码右侧的代码,但还允许您使用符号执行预处理器技巧,例如在宏上使用###从宏参数构造变量名和字符串的参数,内联函数无法做到这一点:

#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 );

这真的存在吗?如果是这样,它叫什么,所以我可以进一步研究它?它是如何工作的?它是 C/C++ 标准的一部分吗?

4

1 回答 1

1

下面的方法呢?

#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 );
于 2021-08-03T10:32:42.497 回答