-1

I have this const array of function pointers:

const callback_t callbacks[] =
{
    func1,
    func2,
    func3,
    func4,
    func5
};

and I would like to add C Compile-Time assert to ensure that func1 is placed first within the array. Something like that:

C_ASSERT(callbacks[0] == func1);

after pre-preocessor stage this is expanded to:

extern char __C_ASSERT__272[( callbacks[0] == func1)?1:-1] __attribute__((unused))

but I'm getting compilation error:

error: variably modified '__C_ASSERT__272' at file scope
elady
  • 535
  • 6
  • 22
  • 4
    And what *is* `C_ASSERT`? There's no such macro (which I assume it is) in standard C. – Some programmer dude Apr 25 '18 at 10:05
  • Please show a [MCVE] – Jabberwocky Apr 25 '18 at 10:25
  • Why do you *need* an assert? You've declared the array `const`, so nothing but `func1` can ever be in that position. If you're worried that someone will change the code incompatibly, then that's a job for your unit tests (and good comments to explain *why* `callbacks[0]` must be `func1`). – Toby Speight Apr 25 '18 at 11:35
  • I have added the expansion of the C_ASSERT to the question. I need it in order to prevent a change by mistake (by someone else). The example in the question is naturally minimized than the real code. – elady Apr 25 '18 at 11:42
  • I am voting to reopen. Selected duplicate is not accurate: `_Static_assert` would also not compile. – user694733 Apr 26 '18 at 06:44

1 Answers1

0

You can't. Values of variables (callbacks[0] in this case) cannot be used in constant expressions in C. Not even if variable is declared const.

You have to do either runtime assertion or check, or add big comment next to array definition saying /* func1 must be first! */.

user694733
  • 15,208
  • 2
  • 42
  • 68