I have to write some functions with a significant amount of constant in it in a relatively small amount of lines.
( Don't bother about the way I wrote the formula, it's there to simply express the fact that I have a lot of constants in a small package, this specific example is small too, in practice I have a minimum of 6-7 constants for each function )
T foo( T x )
{
return k1 * k2 * x - k3;
}
Assuming that I'm not interested in declaring the constants as static ( it will also cause problems with the naming convention in my specific case ) const T k1 = 42;
, I would like to find an alternative .
A viable alternative can be
T foo( T x )
{
return uint32_t{42} * uint32_t{21} * x - uint32_t{33};
}
At this point there are 2 main problems:
- I'm not sure if this kind of declaration will create an entire object or just "a number"
- it's a C++ only solution and I'm writing really simple functions that should be C99+ compatible .
Why I would like to do this ?
It's simple, the values for this constants are highly variable, really small values or big values, with really small values there is a significant amount of space wasted, plus this constants are math constants so they will never change and I can optimize this section right from the first release.
There is also another aspect, the default type for numeric constants is a signed integer, I would like to go for an unsigned integer type of arbitrary size.
The problem with the static declaration const T k1 = 42;
outside the functions, is that different constants have the same name, the value of the constant is different because the function is different, but the name of the constant, mathematically speaking, is the same, so with this solution I'll end up having multiple declarations of the same variable in the same scope. That's why I can't use names or this kind of declarations .
Do you have any idea for writing this in a way that is compatible with both C++ and C ?