how do static variables inside functions work?

后端 未结 3 2237
花落未央
花落未央 2021-02-19 04:20

In the following code:

int count(){
    static int n(5);
    n = n + 1;
    return n;
}

the variable n is instantiated only once a

3条回答
  •  花落未央
    2021-02-19 05:16

    It's quite likely that this variable will be handled just as ordinary global variable by gcc. That means the initialization will be statically initialized directly in the binary.

    This is possible, since you initialize it by a constant. If you initialized it eg. with another function return value, the compiler would add a flag and skip the initialization based on the flag.

提交回复
热议问题