gpt4 book ai didi

c - 用非常量值初始化静态变量

转载 作者:太空狗 更新时间:2023-10-29 17:08:44 25 4
gpt4 key购买 nike

来自21世纪的C书:

Static variables, even those inside of a function, are initialized when the program starts, before main, so you can’t initialize them with a nonconstant value.

//this fails: can't call gsl_vector_alloc() before main() starts
static gsl_vector *scratch = gsl_vector_alloc(20);

This is an annoyance, but easily solved with a macro to start at zero and allocate on first use:

#define Staticdef(type, var, initialization) \ 
static type var = 0; \
if (!(var)) var = (initialization);

//usage:
Staticdef(gsl_vector*, scratch, gsl_vector_alloc(20));

我不明白这个宏有什么不同。预处理后它做的事情不完全一样吗?


最佳答案

Doesn't it do exactly the same thing after preprocessing?

不,两者的行为不一定相同。

此初始化保证运行一次:

static int i = 42; /* Initialisation */

这个作业

static int i = 0;
if (!i) /* line X */
i = 42; /* Assignment */

不是,因为每次程序流到达第 X 行并且 i 等于 0 然后 i 设置42(再次)。

例子:

#include <stdio.h>

void foo(int inew)
{
static int i = 42;

printf("%d\n", i);

i = inew;
}

void bar(int inew)
{
static int i = 0;
if (!i)
i = 42;

printf("%d\n", i);

i = inew;
}

int main(void)
{
foo(43);
foo(0);
foo(44);

printf("\n");

bar(43);
bar(0);
bar(44);

return 0;
}

运行它,看看区别:

42
43
0

42
43
42

关于c - 用非常量值初始化静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26717009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com