我们如何使用嵌套 if else 和 #define 预处理器
How do we use nested if else with #define preprocessor
#define len(a) if (a == 8) 1 \
else if (a == 3) 0 \
else -1
此代码只是我们如何使用嵌套 if else 的示例。
我不想使用三元运算符,因为在那种情况下我不能使用 else if 语句。
不要滥用预处理器。使用真实函数:
constexpr auto len(int const a) {
if (a == 8) return 1;
if (a == 3) return 0;
return -1;
}
inline __attribute__((always_inline)) int len(const int a)
{
switch(a)
{
case 8: return 1;
case 3: return 0;
}
return -1;
}
在宏中编写嵌套或不嵌套 if
语句没有问题,或者至少在尝试将语句包装在宏中时不会出现比平时更多的问题。但请注意,我使用了 语句 ,在 C 或 C++ 中没有 if
表达式,除了您不想使用的三元运算符。
所以如果你想在宏中嵌套 if
s 语句,你可以做类似
#define stmt(c1, c2) \
if (c1) \
do_1(); \
else if (c2) \
do_2(); \
else \
do_3()
(请注意,转义行尾的方法是使用 \
而不是 /
)。如果您想要一个表达式,则必须使用三元运算符或其他答案中所示的函数。好吧,即使您需要语句,我也建议您使用函数而不是宏。
如果您可以使用 GNU 扩展并坚持使用带有 if
-else
分支的宏,您可以使用 compound statement expression:
#define len(a) ({ \
int _res = -1; \
if ((a) == 8) _res = 1; \
else if ((a) == 3) _res = 0; \
(_res); })
这在 C 和 C++ 中都有效。不幸的是,这样的复合语句不能用在常量表达式中。
回复:"I don't want to use ternary operator as in that case i can't use else if statement" - 是的,您不能在三元运算符中使用 else if
。但是你可以使用另一个三元运算符:
int x = a == 8 ? 1
: a == 3 ? 0
: -1;
#define len(a) if (a == 8) 1 \
else if (a == 3) 0 \
else -1
此代码只是我们如何使用嵌套 if else 的示例。 我不想使用三元运算符,因为在那种情况下我不能使用 else if 语句。
不要滥用预处理器。使用真实函数:
constexpr auto len(int const a) {
if (a == 8) return 1;
if (a == 3) return 0;
return -1;
}
inline __attribute__((always_inline)) int len(const int a)
{
switch(a)
{
case 8: return 1;
case 3: return 0;
}
return -1;
}
在宏中编写嵌套或不嵌套 if
语句没有问题,或者至少在尝试将语句包装在宏中时不会出现比平时更多的问题。但请注意,我使用了 语句 ,在 C 或 C++ 中没有 if
表达式,除了您不想使用的三元运算符。
所以如果你想在宏中嵌套 if
s 语句,你可以做类似
#define stmt(c1, c2) \
if (c1) \
do_1(); \
else if (c2) \
do_2(); \
else \
do_3()
(请注意,转义行尾的方法是使用 \
而不是 /
)。如果您想要一个表达式,则必须使用三元运算符或其他答案中所示的函数。好吧,即使您需要语句,我也建议您使用函数而不是宏。
如果您可以使用 GNU 扩展并坚持使用带有 if
-else
分支的宏,您可以使用 compound statement expression:
#define len(a) ({ \
int _res = -1; \
if ((a) == 8) _res = 1; \
else if ((a) == 3) _res = 0; \
(_res); })
这在 C 和 C++ 中都有效。不幸的是,这样的复合语句不能用在常量表达式中。
回复:"I don't want to use ternary operator as in that case i can't use else if statement" - 是的,您不能在三元运算符中使用 else if
。但是你可以使用另一个三元运算符:
int x = a == 8 ? 1
: a == 3 ? 0
: -1;