Friday, February 17, 2017

PowerShell surprise: functions can break out of a loop in their caller

One might expect that the Break statement inside a function would cause the function to exit, or at least do nothing to its caller. I was very surprised to learn that it can indeed affect the control flow in the calling scope. Take this trivial function:

Function BreakTest {Break}

And this calling code:

for ($a = 0; $a -lt 5; $a++) {
 for ($b = 0; $b -lt 3; $b++) {
  BreakTest; "a = $a; b = $b"
 }; $a
}

The sprinkle of strings that one would expect to be output by the innermost "for" loop never comes; calling BreakTest exits the $b loop. The program just outputs the numbers from 0 to 4. If you remove the function call, you do indeed get a bunch of texts, with the plain $a's 0 through 4 interspersed.

No comments:

Post a Comment