Why can't functions have static variables?

I'm sure this has been brought up before but as I couldn't find any previous discussion on it:

The following is not allowed:

func next() -> Int {
    static var v = 0 // ERROR: Static properties may only be declared on a type
    v += 1
    return v
}

But it is trivial to work around this:

func next() -> Int {
    struct S { static var v = 0 }
    S.v += 1
    return S.v
}
print(next()) // 1
print(next()) // 2
print(next()) // 3

So what is the rationale behind not allowing static variables in functions?

1 Like

For the most part, only that nobody has proposed or tried to implement them. One issue would be that static variables in generic contexts would likely need to be instantiated for each set of generic arguments, which would require additional runtime support similar to what we'd need to support static vars in generic types.

4 Likes

Wow, structs can be declared inside of functions? I've never seen that.

It also stretches the meaning of static, which currently means "associated with a type instead of an instance". (Admittedly the only reason it means this is because of C++ going the other direction, from the original C static-lifetime-as-opposed-to-auto to static-as-opposed-to-instance, but…)

1 Like

Doesn’t C++ provide both meanings?

Jonathan

It does, but C++ is a language where many keywords or symbols have multiple meanings based on context. (C++ has many positive features but I don't consider this one of them!)

2 Likes