简体   繁体   English

从c中的函数初始化一个静态const变量

[英]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 我收到的错误是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. 在线阅读后我明白这个问题是因为编译器在编译时评估static const表达式,因此无法知道该值应该是什么。

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. 也许我应该澄清一下getSize中的逻辑只是一个例子,它也可能包含从特定文件中检索文件大小的逻辑。

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. 与C ++不同,您不能使用C中的函数结果初始化全局变量,而只能使用编译时已知的实常数来初始化全局变量。

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: 不要再声明static const int size = ...了,但是写下:

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() . 这样, SomeComplexFunctionOfYours()只在第一次调用getSize()时被调用一次。 There is a small price to be paid: each time you invoke getSize() , a test needs to be performed. 需要付出很小的代价:每次调用getSize() ,都需要执行测试。

Or you can initialize it explicitely like this, but then size cannot be const anymore: 或者你可以像这样明确地初始化它,但是那时size不能再为const

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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