# Why init function for a class variable is executed twice?

**URL:** <https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602>\
**Category:** Help & Support\
**Created:** [April 24, 2023, 1:36am UTC](https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602 "2023-04-24T01:36:48Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dimagog](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/dimagog/32/140_2.png) [@Dimagog](https://forum.crystal-lang.org/u/Dimagog)\
**Post date:** [April 24, 2023, 1:36am UTC](https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602/1 "2023-04-24T01:36:48Z")

</div>

The following code, when run, prints “inside init” twice, why?  
[https://play.crystal-lang.org/#/r/exio](https://play.crystal-lang.org/#/r/exio)

```auto
class Test
  @@global : Int32
  @@global = init
 
  def self.init
    puts "inside init"
    1
  end
end

```

Output:

```plaintext
inside init
inside init

```

---

<div class="post-metadata">

**Author:** ![zw963](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/zw963/32/1623_2.png) [@zw963](https://forum.crystal-lang.org/u/zw963)\
**Post date:** [April 24, 2023, 4:57am UTC](https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602/2 "2023-04-24T04:57:38Z")

</div>

I don’t know why, but you can init it when declare it.

```crystal
class Test
  @@global : Int32 = init

  def self.init
    puts "inside init"
    1
  end
end

```

in this case, it execute only once.

---

<div class="post-metadata">

**Author:** ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)\
**Post date:** [April 24, 2023, 10:35am UTC](https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602/3 "2023-04-24T10:35:36Z")

</div>

It seems that the compiler generates two calls to the var initializer `Test::global:init`, instead of just one.  
This looks like a compiler bug.

---

<div class="post-metadata">

**Author:** ![HertzDevil](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/hertzdevil/32/1023_2.png) [@HertzDevil](https://forum.crystal-lang.org/u/HertzDevil)\
**Post date:** [April 24, 2023, 10:46am UTC](https://forum.crystal-lang.org/t/why-init-function-for-a-class-variable-is-executed-twice/5602/4 "2023-04-24T10:46:33Z")

</div>

Reminds me of [Is there any optimization for constants? - #11 by straight-shoota](https://forum.crystal-lang.org/t/is-there-any-optimization-for-constants/5341/11)
