Initialising a static const variable from a function in c

◇◆丶佛笑我妖孽 提交于 2020-06-27 12:03:33

问题


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.


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/54831046/initialising-a-static-const-variable-from-a-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!