Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising a static const variable from a function in c

I have recently run into some trouble while trying to perform the following logic:

static const int size = getSize();

int getSize() {
    return 50;
}

The error I have received is initialiser element is not constant

Having read online I understand that this issue is because the compiler evaluates the static const expression at compilation and therefore cannot know what the value is supposed to be.

My question is how do I get around this?

If I have a library that contains many functions but they all require this logic how are they supposed to use it without having to calculate it each time?

And even if they have to, what if the logic itself can change throughout runtime but I only ever want the first value I receive from the function?

Perhaps I should clarify that the logic in getSize is just an example, it could also contain logic that retrieves the file size from a specific file.

like image 760
mark Avatar asked Sep 08 '25 07:09

mark


1 Answers

Unlike in C++ you cannot initialize global variables with the result of a function in C, but only with real constants known at compile time.

You need to write:

static const int size = 50;

If the constant must be computed by a function you can do this:

Dont declare static const int size = ... anymore, but write this:

int getSize()
{
  static int initialized;
  static int size;

  if (!initialized)
  {
    size = SomeComplexFunctionOfYours();
    initialized = 1;
  }

  return size;  
}

int main(void)
{
  ...
  int somevar = getSize();
  ...

That way SomeComplexFunctionOfYours() will be called only once upon the first invocation of getSize(). There is a small price to be paid: each time you invoke getSize(), a test needs to be performed.

Or you can initialize it explicitely like this, but then size cannot be const anymore:

static int size;

void InitializeConstants()
{
  size = SomeComplexFunctionOfYours();
}

int main(void)
{
  InitializeConstants();
  ...
  int somevar = size;
  ...
like image 117
Jabberwocky Avatar answered Sep 10 '25 01:09

Jabberwocky