# Calculating variables at compile time

**URL:** <https://forum.arduino.cc/t/calculating-variables-at-compile-time/262409>\
**Category:** Programming\
**Created:** [October 9, 2014, 10:23pm UTC](https://forum.arduino.cc/t/calculating-variables-at-compile-time/262409 "2014-10-09T22:23:49Z")\
**Posts on this page:** 1\
**Showing post:** 18

<div class="post-metadata">

**Author:** ![nickgammon](https://avatars.discourse-cdn.com/v4/letter/n/45deac/32.png) [@nickgammon](https://forum.arduino.cc/u/nickgammon)\
**Post date:** [October 13, 2014, 3:39am UTC](https://forum.arduino.cc/t/calculating-variables-at-compile-time/262409/18 "2014-10-13T03:39:52Z")

</div>

It turns out it can be done, with a bit of a pre-processing trick.

Add a .h file to your project (new tab in the top RH corner) like this:

**myTable.h**

```cpp
#if __COUNTER__ == 0
    const float myTable [ENTRIES] = {
    #include "myTable.h"
#elif __COUNTER__ < (ENTRIES * 3)
  FUNC(( __COUNTER__ / 3) - 1),
    #include "myTable.h"
#else
    };  // end of myTable
#endif

```

This rather obscure file calls itself recursively to generate the table (calling FUNC for each entry).

Now the main file:

```cpp
#define ENTRIES 128

const float AccumMax = 3;
const float aFreq = 1.2;
const float lowA = 16;
const float samplingfrequency = 1000;

#define FUNC(x) AccumMax * ((pow( aFreq, x-21 ) * lowA)/samplingfrequency)

#include "myTable.h"
 
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  
  for (int i = 0; i < ENTRIES; i++)
    Serial.println (myTable [i], 4);
  }  // end of setup

void loop () { }

```

This uses a compiler feature, the **COUNTER** symbol, which the compiler adds one to, each time it is used. When it is zero, the include file creates a table. Then it recurses, and for each recursion (up to ENTRIES) it generates another table line. Then when the limit is reached it finishes off the table.

In this line:

```cpp
  FUNC(( __COUNTER__ / 3) - 1),

```

We divide by 3 because **COUNTER** appears 3 times in the include file, and thus goes up by 3 each time. And by the time it is used we have 3 / 3 which is 1, so to get back to a zero-relative argument we have to subtract one.

* * *

Now I'm **not** necessarily recommending this because for one thing it is obscure, and for another, for a larger table the compiler eventually complains:

```cpp
myTable.h:6:25: error: #include nested too deeply

```

---

_[View the full topic](https://forum.arduino.cc/t/calculating-variables-at-compile-time/262409)._
