【问题标题】:GCC: blocks in assignments with return values making macros easier?GCC:带有返回值的赋值块使宏更容易?
【发布时间】:2020-07-31 09:56:40
【问题描述】:

我隐约记得 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++ 标准的一部分吗?

【问题讨论】:

    标签: gcc macros gcc-extensions


    【解决方案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 );
    

    【讨论】:

    • thx,非常干净地实现了我的示例的目标,但要明确的是,我不是在寻找一个干净或可移植的解决方案,而是寻找一个允许“返回”语句的功能的名称。 ...
    • @SwissFrank 对于这种情况,只需使用返回值的函数。 return 1;return 0; 适用于 int 类型的函数。不要在宏上浪费时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2020-10-02
    • 2021-08-13
    • 1970-01-01
    • 2022-01-23
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多