# Calling global function before declaration

**URL:** <https://forums.swift.org/t/calling-global-function-before-declaration/35059>\
**Category:** Using Swift\
**Created:** [April 3, 2020, 2:37pm UTC](https://forums.swift.org/t/calling-global-function-before-declaration/35059 "2020-04-03T14:37:46Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [April 5, 2020, 11:07am UTC](https://forums.swift.org/t/calling-global-function-before-declaration/35059/6 "2020-04-05T11:07:48Z")

</div>

I think this is a bug, here's a reduced example:

```swift
// This program compiles and print 0 when run:
print(x) 
let x = 123

```

```swift
// This program compiles and crashes (segmentation fault 11) when run:
print(x) 
let x = [1, 2, 3]

```

* * *

> [@and](#):
>
> But I noticed, that nowadays this code is legal

Are you sure that this hasn't always been the case? See for example this old perhaps somewhat related thread:

> [@Can anyone please explain this behavior?](https://forums.swift.org/t/can-anyone-please-explain-this-behavior/4082/5):
>
> This worrying little program compiles:
> 
> ```swift
> func f() -> Int {
> return a
> }
> let a = f()
> 
> ```
> 
> It also compiles if you print(a) at the end, and it will print 0.
> 
> If we replace Int with [Int] it will still compile but crash when run.
> 
> And also this:
> 
> AnotherFile.swift containing:
> 
> ```swift
> func f() -> Int {
> return a
> }
> let a = f()
> 
> ```
> 
> main.swift containing:
> 
> ```swift
> print(a)
> 
> ```
> 
> Compile, run (for eternity, at 0% CPU).

* * *

If it the behavior _has_ changed in Swift 5.2, then it seems like more/different bugs have been introduced, since the example in the end of the following old post now compiles (though @jrose says at the end of the post that it is important to make sure it continues to be rejected):

> [@Can anyone please explain this behavior?](https://forums.swift.org/t/can-anyone-please-explain-this-behavior/4082/8):
>
> Yep, it really is a long-standing bug. Script-mode top-level locals are treated as globals (module-scope bindings) by the compiler, but their initial bindings are evaluated eagerly instead of lazily (as you’d want in a script). Taken together, this means that you can get this completely unsafe behavior. So, why is ‘a’ accepted but ‘b’ not in your original example? func foo() -\> Int { return b } let a = 1 let b = 2 print(foo()) The secret to the current behavior is that script mode is exe…

---

_[View the full topic](https://forums.swift.org/t/calling-global-function-before-declaration/35059)._
