简体   繁体   中英

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.

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;
  ...

The compiler needs to know the value of your constant variable at the compilation time, because its a constant.

Also you can't initialize a variable with a function.

You should do something like this :

#define SIZE 50

static const int size = SIZE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM