views:

95

answers:

4
+1  Q: 

replacing #define

Hi, i want to replace a

#define INTERVAL_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 case statements. How to go about converting this? Replacing the switch with if is the only option?

Thanks, gokul.

A: 

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

Oli Charlesworth
Presumably because `b` has different values in different places.
therefromhere
@therefromhere: But each one will need to be a compile-time constant if the OP's currently using them in a switch statement.
Oli Charlesworth
@Oli: The OP is likely to use it as in `case INTERVAL_MASK(2):`, `case INTERVAL_MASK(17):`, ...
DarkDust
@James McNellis: Oops... Sorry. Deleted my comment :)
AndreyT
@DarkDust: this could well be the case, yes.
Oli Charlesworth
+6  A: 

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.

James McNellis
A: 

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.

Ruel
A: 

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.

codymanix