mardi 1 août 2017

ANSI-C constant-expression function like C++ constexpr?

Putting it simple, is there an ANSI-C way of making a function a constant expression?

  1. Pure ANSI-C but GNU extensions are acceptable - NO C++, though.
  2. Preferably without relying on macros.
  3. Something that surely behaives like the C++ constexpr and won't be solved at run time.

Background:

I need to implement a lot of math in an embedded processor that does not have floating point, so I am using fixed point in my application.

I don't like to see cryptic constants in my header files, though. My hardware needs several floating-point constants (e.g. 130.7 microseconds, 0.2503 mJ) and I'd really like to be able to read (and change) my constants as the parts datasheet values are listed.

At a given moment, my hardware needs to use this constants, for example, to fill in a timer reload value, and, since the values are constant, i'd like to have somthing like:

static const int values_table[] =
{
    _Time( 123.45 ),    // 123.45 microseconds.
    // ...
};

// ...

int conv_to_timer( x ) { /* my calculations - all const. */ }

// ...

void my_code( void )
{
    // ...
    timer_reload = conv_to_timer( values_table[ index ] );

One approach would be making my _Time( x ) macro to do all calculations needed for the timer values but it is not flexible (i.e. not comparable against someting outside) neither portable (a different hardware would demand a different calculation).

Any suggestions for an elegant approach, please?

Aucun commentaire:

Enregistrer un commentaire