Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional compilation depending on function argument?

I searched far and wide and information on the net seems to suggest that conditional compilation using the preprocessor works exclusively on environment variables.

Basically, I would like to have an inline function or macro perform different operations based in its input arguments. Example of what I want to achieve:

inline void foo(int x) {

    #if (x < 32)

        register0 |= (1 << x);

    #else

        register1 |= (1 << (x - 32));

    #endif

}

The main goal here is that the resulting inline code will not contain conditional code for constant inputs.

Basically, I currently program for a microcontroller (lpc213x) and would like to have an inline function or macro to do pin configuration setup. Since pin configurations are split across multiple registers (e.g. 0 and 1 above), I would like to perform some conditional checks to decide which register is supposed to be written to for a given pin constant.

However, the pin configurations are all constant at compile time, so I would like to eliminate the conditional checks from compile code. I know that optimization would likely get rid of unnecessary conditionals anyway, but I'm wondering whether there is a way to achieve this behavior explicitly, because I might need to disable optimization in the future.

Thanks,

FRob

like image 979
FRob Avatar asked Nov 29 '11 10:11

FRob


People also ask

What statements are used for conditional compilation?

The compiler directives that are used for conditional compilation are the DEFINE directive, the EVALUATE directive, and the IF directive.

What is meant by conditional compilation?

In computer programming, conditional compilation is a compilation technique which results in an executable program that is able to be altered by changing specified parameters.

What is conditional compilation in VB net?

Conditional compilation is the ability to specify that a certain block of code will be compiled into the application only under certain conditions. Conditional compilation uses precompiler directives to affect which lines are included in the compilation process.


1 Answers

With C++, you could use template functions, like this:

template <bool B>
void doSetRegister(int x);

template<>
inline void doSetRegister<true>(int x) {
    register0 |= (1 << x);
}

template<>
inline void doSetRegister<false>(int x) {
    register1 |= (1 << (x - 32));
}

template <int X>
inline void setRegister() {
    doSetRegister<X <= 32>(X);
}

int main() {
    setRegister<1>();
    setRegister<33>();
}
like image 77
king_nak Avatar answered Oct 21 '22 21:10

king_nak