在 C 中是否可以有一个带有条件 break 语句的宏

in C is it possible to have a macro with conditonal break statement

下面的思路在C中是否可行?

我到达失败了。 (使用在线 C 编译器对此进行测试)

也许可以使用 GOTO 解决,但这不是我们想要的。

只是理论上的,如果我还缺少任何其他解决方案,但我的想法是让状态机更高效一点。

#include <stdio.h>
#include <stdint.h>

uint8_t shouldhavebreaked = 0;
#define BREAK_CONDITIONAL(x,y) do { if(x == y) { shouldhavebreaked = 1; break ;}  } while(0)

int main()
{
    uint8_t swh = 0;

    switch (swh)
    {

    case 0:
 
    /*if state is same, break, otherwise fall-through*/
    BREAK_CONDITIONAL(swh, 0);

    case 1:
        printf("failed \n");
        break;

    }
    printf("changed? %d \n",shouldhavebreaked);
    return 0;
}

您可以使用不那么时髦的 if(){} else:

而不是 funky do{}while()
#define BREAK_CONDITIONAL(x,y) if(x == y) { shouldhavebreaked = 1; break; } else

并且在宏中过度使用括号是一个好习惯:


#define BREAK_CONDITIONAL(x,y) if((x)==(y)) { shouldhavebreaked=1;break;} else

那种宏没有任何意义(除非你想让代码更难阅读、理解和维护。它也会更容易出错)。避免成为瘟疫。它们看起来像函数,但实际上不是。

如果我从@wildplasser 的回答中隐藏宏,你能猜出这是什么废话吗?

    if(c)
    {
        BREAK_CONDITIONAL(a,b) c = a+b;
    }