static in local func

how dangerous to have a static var in a local func?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void MyListWidget::sortSongName()
{
    static int a = 0;
    if ( a == 0 )
    {
       sortItems(Qt::AscendingOrder);
       a = 1;
    }
    else 
    {
       sortItems(Qt::DescendingOrder);
       a = 0;
    }
}
It is absolutely safe.
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. Footnote: The implementation must not introduce any deadlock around execution of the initializer. - IS


Except for one edge case; if control re-enters the declaration recursively while the variable is in the process of being initialised, it engenders undefined behaviour.

Example from the IS:
1
2
3
4
5
6
int foo(int i) {

    static int s = foo(2*i); // recursive call - undefined

    return i+1;
}
As a small note to add: static variables in functions can be very useful, such as keeping track of what the arguments were the last time the function was called. You could detect sign flips between calls, increasing/decreasing values between calls, etc, without changing the interface with the function caller.

Just follow with JLBorges said and make sure it doesn't result in undefined behavior.
i see thank you all guys
Topic archived. No new replies allowed.