Jens
1
And If so, what should it print?
test.swift:
func f() { g() }
f()
print(x)
var x = 100
func g() { x += 1 }
The current behavior is that it compiles fine and prints 1 (why not eg 101?):
$ swiftc --version
Apple Swift version 5.2 (swiftlang-1103.0.32.1 clang-1103.0.32.29)
Target: x86_64-apple-darwin19.4.0
$ swiftc test.swift && ./test
1
I think it looks like an accepts invalid bug because (among other things) …
… look what happens if `x` is an `Array` instead of an `Int`.
func f() { g() }
f()
print(x)
var x = [1, 2, 3]
func g() { x.append(4) }
$ swiftc test.swift
$ ./test
Segmentation fault: 11
That is, it compiles fine, but crashes at runtime.
Possibly related threads and bugs.
Can anyone please explain this behavior? - #8 by jrose
Compiler bug or feature? - #2 by Jens
Calling global function before declaration
SR-2730
SR-2727
SR-284
SR-11534 (Note that this one is open, yet it seems to have been "fixed" in a way that makes my examples above "work" ...)
1 Like
Assuming you are running this in a Playground, no it doesn't compile because both x and g() are not declared before they are used.
Try this :
var x = 100
func g() { x += 1 }
func f() { g() }
f()
print(x)
Jens
3
No (you need to re-read my post I think), see for example this:
(That is, it is a command line program, which compiles, and prints "1".)
Well, this is the entire point of my post, that my example program (at least somewhat) unexpectedly compiles, as is. The order of things in the program is very deliberate, I'm not asking for help about how to get it to compile (it does compile!), I'm asking if this exact program demonstrates an accepts-invalid-bug in the compiler or not.
2 Likes