开发者

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 debuggi开发者_Python百科ng 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). 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...

#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. This works for C++ as well as for 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜