[swift-users] inout params seem to have undefined behavior

Joe Groff jgroff at apple.com
Mon Jun 13 11:45:40 CDT 2016


> On Jun 11, 2016, at 10:29 AM, Karl Pickett via swift-users <swift-users at swift.org> wrote:
> 
> I don't believe the (spartan) docs address this case:
> 
> func foo(inout a: [Int], inout b: Int) {
>    let acopy = a
>    a = [4, 5, 6]
>    print(acopy)  // prints "[1, 2, 3]"
>    b = 99
>    print(a)   // prints "[4, 5, 6]"
>    print(acopy)  // prints "[1, 2, 99]" (e.g. a let variable changed!)
> }
> 
> var arr = [1,2,3]
> 
> foo(&arr, b: &arr[2])
> 
> print(arr)  // prints "[4, 5, 6]"
> 
> 
> Is this code "undefined", meaning the spec / doc doesn't specifically
> say what should be happening?  For instance, I can't believe a let
> variable gets changed.  The docs also say inout changes the original
> value when the function ends, not in the middle as is happening here.

It's not undefined behavior in that we try to ensure that memory safety is still preserved when inout parameters alias, but it is *unspecified* when updates to an inout parameter will be written back to the original argument. You should avoid aliasing inout parameters for this reason.

-Joe



More information about the swift-users mailing list