# Does Julia Need a C++ style \`static\` keyword?

**URL:** <https://discourse.julialang.org/t/does-julia-need-a-c-style-static-keyword/29176>\
**Category:** Internals & Design\
**Created:** [September 25, 2019, 8:24pm UTC](https://discourse.julialang.org/t/does-julia-need-a-c-style-static-keyword/29176 "2019-09-25T20:24:33Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 26, 2019, 10:27am UTC](https://discourse.julialang.org/t/does-julia-need-a-c-style-static-keyword/29176/6 "2019-09-26T10:27:36Z")

</div>

You can use an inner constructor (eg in the example below, with validation):

```julia
let counter = 0
    global get_counter() = counter

    struct Foo
        x::Int
        function Foo(x)
            x > 0 || error("invalid x")
            counter += 1
            new(x)
        end
    end
end

```

which works like this (note counter is only incremented when you create a valid `Foo`):

```julia
julia> get_counter()
0

julia> Foo(1)
Foo(1)

julia> get_counter()
1

julia> Foo(-1)
ERROR: invalid x
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] Foo(::Int64) at /tmp/foo.jl:7
 [3] top-level scope at REPL[41]:1

julia> get_counter()
1

```

That said, global mutable state is difficult to reason about and may preclude some compiler optimizations, so it is generally avoided in Julia. Instead of porting code in C++ style, I would recommend finding another solution.

---

_[View the full topic](https://discourse.julialang.org/t/does-julia-need-a-c-style-static-keyword/29176)._
