Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize static variable with the argument of a function

How can I do something like this?

void function(int n)
{
    static int number = n;
    .
    .
    .
}

1 Answers

If you want to initialize the static variable to n during the first invocation of the function, you can do it like this:

void function(int n)
{
    static int initialized = 0;
    static int number;

    if (!initialized) {
        number = n;
        initialized = 1;
    }
    .
    .
    .
}

You can't initialize number to n directly since number is initialized at compile time, while n is known only at run time.

like image 181
rustyx Avatar answered Nov 21 '25 10:11

rustyx



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!