Search code examples
swiftscopeflow-control

Different control flow statement can have the same title


There are 2 different nested loops and each of them has a break statement to break the outer loop under their certain conditions.

I wonder if I mark the 2 outer loops with the same title, would this triggers a confusion for the break statement?

I then tried the following code snippets

//#1
outterLoop: for x in 1...3 {
    innerLoop: for y in 1...3 {
        if x == 3 {
            break outterLoop //break the "outterLoop"
        } else {
            print("x: \(x), y: \(y)")
        }
    }
}

//#2
outterLoop: for a in 1...3 {
    innerLoop: for b in 1...3 {
        if b == 3 {
            break outterLoop //break the "outterLoop"
        } else {
            print("a: \(a), b: \(b)")
        }
    }
}

It turns out the code works just fine and there is no re-declaration issue appears. I think it might be related to the scope topic. The first break can only see the outterLoop in the #1 code block and the second break can only see the outterLoop at the scope it located, AKA, the #2 code block. As a result, the invisible scope limited the variable that the inner break can "see"

Question: Am I understood it correct? If not, please correct me. And even if I was not wrong, I believe I used informal and imprecise descriptions. Would be nice if you can give me a more formal and precise description.

Many thanks


Solution

  • “The scope of a labeled statement is the entire statement following the statement label. You can nest labeled statements, but the name of each statement label must be unique.”

    Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.2).” iBooks. https://itun.es/de/jEUH0.l

    The scope of the first outterLoop: label is the first for-loop, and the scope of the second outterLoop: label is the second for-loop.

    Therefore break outterLoop inside the first loop can only refer to the first outterLoop: label, and the same is true for the second loop.

    This is different from C, where the goto statement and its target label only need to be in the same function, and consequently no two labels with the same name can be defined within the same function.