Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let static function variable take value of parameter in C

I am writing a data mashing function where I'm modifying audio data over time for a sort of dynamic bit-crusher audio filter. It is convenient for me to use static variables because their values carry over between function calls and this helps me achieve some interesting time-based effects by incrementing and so forth across rendering callbacks.

For example, one effect uses a sin function to modulate some sound effect over time. Like so:

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

So I wish theta to be initialized once and than modified over time. Likewise, top wants to be static variable because I modify it later in the function also. In addition, top should take on the value of parameter n because n changes based on program state. But when I go to assign n to top, I get the compiler error

Initializer element is not a compile-time constsant.

Is there a way to assign a parameter to a static variable? Is there another way to accomplish what I want without static variables? I am aware I could use instance variables but I find that to be too much.

like image 877
Alex Bollbach Avatar asked Mar 26 '26 04:03

Alex Bollbach


1 Answers

static variables are initialized before the program execution begins, so you cannot use a variable value to initialize a static variable. You'll need a compile-time constant value to initialize the static variable.

Quoting C11 standard, chapter §6.2.4, Storage durations of objects (emphasis mine)

[..] 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.

However, you can always assign a new value to the static variable.

That said, coming to the initialization part, as per chapter §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
- ...

so, you need not initialize the static floats explicitly to 0. You can assign any value, whatsoever later in the code.

like image 64
Sourav Ghosh Avatar answered Mar 28 '26 17:03

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!