从C中的函数初始化静态const变量 [英] Initialising a static const variable from a function in c

查看:93
本文介绍了从C中的函数初始化静态const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在尝试执行以下逻辑时遇到了一些麻烦:

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

static const int size = getSize();

int getSize() {
    return 50;
}

我收到的错误是 initialiser元素不是常量

可以在线阅读,我知道这个问题是因为编译器评估了静态常量编译时的表达式,因此不知道该值是什么。

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?

也许我应该澄清一下getSize中的逻辑只是一个例子,它也可能包含从特定文件中检索文件大小的逻辑。

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.

推荐答案

与C ++不同,您不能使用C中的函数结果来初始化全局变量,而只能使用在编译时已知的实常数来初始化。

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.

您需要编写:

static const int size = 50;

如果常量必须由函数计算,则可以执行以下操作:

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

不再声明 static const int size = ... ,而是这样写:

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

那样 SomeComplexFunctionOfYours()在第一次调用 getSize()时仅被调用一次。付出的代价很小:每次调用 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.

或者您可以像这样显式地初始化它,但是 size 不再是 const 了:

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

这篇关于从C中的函数初始化静态const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆