Here's a riddle.
Imagine I have the following C++ function:
template<uint8_t MASK>
uint8_t Foo(uint8_t val)
{
uint8_t step = 0;
uint8_t result = 0;
if(MASK & 0x01) {result |= (val & 0x01) >> step; ++step;}
if(MASK & 0x02) {result |= (val & 0x02) >> step; ++step;}
//...etc...
if(MASK & 0x80) {result |= (val & 0x80) >> step; ++step;}
return result;
}
When I instantiate this function as such (all values below are just examples values):
uint8_t someval = Foo<0xAA>(44);
The compiler optimizes out the if statements in Foo() because it knows at compile time what the result of said if() statement are.
This is nice and well, but trying to do the same in C is problematic because of the creation of the local variable step.
If step wasn't there, you could do a large #define like this:
#define Foo(MASK, val) (\
((MASK & 0x01) ? (val & 0x01) : 0) | \
((MASK & 0x02) ? (val & 0x02) : 0) | \
...etc...
((MASK & 0x80) ? (val & 0x80) : 0) | \
)
But with step, I'm kind of at an impasse. What can I do to obtain the same functionality of C++ template in C for C++ template function with local variables?
Note that using inline C functions is not an answer, as the compiler will not know at compile time the value of MASK, and thus all the comparisons will not be optimized and will accordingly be part of the final compiled output.
Also note that changing the #define to include the result value is also not an answer, since this changes the "function's" signature.
And lastly, I am fully aware that there may be no answer to this riddle.