开发者

Replacing #define

I want to replace a

#define INTER开发者_开发问答VAL_MASK(b) (1 << (b))

with a inline function.

int INTERVAL_MASK(int b)
{
    return (1 << b);
}

But I have a switch case, which uses the preprocessor directive in the case statements. How to go about converting this? Replacing the switch with if is the only option?


The switch case label must have an integral constant expression, so you can't have a function call in the case label.

There is nothing wrong with using a macro for this.

If you are really concerned about using the macro, #define it just before the switch statement and #undef it immediately after the switch statement.

In C++0x, you'll be able to create constexpr functions that can be used in constant expressions, but to the best of my knowledge no compiler actually fully supports that part of C++0x yet.


Why not const int interval_mask = (1 << b);?


An important thing to note about the switch statement is that the case values may only be constant integral expressions.

The only workaround I can think for you, is a bunch of if-else statements. Or, you could just generate the cases from 2 (1 << 1) to 1024 (1 << 10) or to whatever your limit is, programmatically. Means your switch statement will look like:

switch(i) {
    case 2:
        //random stuff
        break;
    ...
    case 1024:
        //random
        break;
    ...
}

There would be a separate code that will generate this. It won't be that hard actually.


as far as I know, functions containing control statements like switch, if and loops are not inlined.

You can be sure if you use a macro.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜