简体   繁体   English

如何将条件语句修饰为表达式?

[英]How to decorate a conditional statement to be an expression?

I want to use condition statement as an expression, such as below, how to make it? 我想使用条件语句作为表达式,例如下面的,如何制作呢?

0, (do {a++;} while (a > 100););

EDIT , the reason I want to do this is I want to add a conditional statement to an existing expression for debugging purpose, the existing expression is in a header file and included by many source files. 编辑 ,我要执行此操作的原因是我想向现有表达式添加条件语句以进行调试,现有表达式位于头文件中,并且包含在许多源文件中。 For example, I want to write some debug message when the previous expression reaches some special value. 例如,当上一个表达式达到某个特殊值时,我想编写一些调试消息。

You simply can't have a do-while statement inside an expression in Standard C++ (there's a GCC-specific extension http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html ). 您根本无法在Standard C ++的表达式中包含do-while语句(存在特定于GCC的扩展名http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html )。 But what are you really trying to achieve? 但是,您真正想要实现的目标是什么? - we may be able to find an elegant alternative... -我们也许能够找到一个优雅的替代方案...

In C++0x, you can get close, ala... 在C ++ 0x中,您可以亲近,...

#include <iostream>

int main()
{
    int a = 10;
    std::cout << (([&]() -> int { do { a--; } while (a > 10); return a; })()) << '\n';
}

Just put it in an inline function. 只需将其放在inline函数中即可。 This works for C++ as well as for C99. 这适用于C ++和C99。 If you have special things that should evaluate at the place of the caller, wrap the call into a macro that does exactly the evaluations that you need. 如果您有特殊的事情需要在调用方进行评估,则将调用包装到一个完全执行所需评估的宏中。

the reason I want to do this is I want to add a conditional statement to an existing expression for debugging purpose, the existing expression is in a header file and included by many source files. 我要执行此操作的原因是,我想向现有表达式中添加条件语句以进行调试,现有表达式位于头文件中,并且包含在许多源文件中。 For example, I want to write some debug message when the previous expression reaches some special value. 例如,当上一个表达式达到某个特殊值时,我想编写一些调试消息。

Use a function. 使用功能。 Mark it inline if you want to define it in the header. 如果要在标题中定义它,请内联标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM