c - 让静态函数变量在C中取参数值

标签 c function initialization local-variables static-variables

我正在编写一个数据混搭函数,其中我正在为一种动态比特 splinter 机音频过滤器随时间修改音频数据。使用静态变量对我来说很方便,因为它们的值在函数调用之间传递,这有助于我通过在渲染回调中递增等实现一些有趣的基于时间的效果。

例如,一种效果使用 sin 函数随时间调制某些音效。像这样:

void mangle(float * data, int n) {

   static bool direction = false;

   static float bottom = 0;
   static float top = n;
   static float theta = 0;

   theta += 5;

// data = sin(theta) etc..

所以我希望 theta 被初始化一次,然后随着时间的推移进行修改。同样,top 想成为静态变量,因为我稍后也在函数中修改它。此外,top 应采用参数 n 的值,因为 n 根据程序状态而变化。但是当我将 n 分配给 top 时,我得到了编译器错误

Initializer element is not a compile-time constsant.

有没有办法将参数分配给静态变量?有没有另一种方法可以在没有静态变量的情况下完成我想要的?我知道我可以使用实例变量,但我发现它太多了。

最佳答案

static 变量在程序执行开始之前被初始化,因此您不能使用变量值来初始化 static 变量。您需要一个编译时常量值来初始化 static 变量。

引用 C11 标准,章节 §6.2.4,对象的存储持续时间(强调我的)

[..] or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

但是,您始终可以分配一个新值给static变量。

也就是说,根据第 6.7.9 章,进入初始化部分,

If an object that has static or thread storage duration is not initialized explicitly, then
- ...
- if it has arithmetic type, it is initialized to (positive or unsigned) zero
- ...

因此,您无需将static float显式初始化为0。您可以在代码后面分配任何值。

关于c - 让静态函数变量在C中取参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35449956/

相关文章:

c - 如果用户在 C 中输入无效选项,则重复菜单并提示

c - 编写函数的两种方法

C++:将 double 转换为字符串的最佳方法是什么?

c++ - 将 LONG 转换为函数指针?

c - 尝试从 C 数组中删除元素时出现意外结果

javascript - 函数中 THIS 关键字的范围?

c++ - 在 C++ 类中初始化静态结构

c - 以 "int x[][n]"作为参数的函数

servlets - 使用特殊的自动启动 servlet 在启动时进行初始化并共享应用程序数据

objective-c - 创建一个用计数 N 初始化的 NSArray,都是同一个对象