Skip to main content
A do-while loop is a post-test control flow structure that guarantees the execution of a code block at least once before evaluating a boolean loop-continuation condition. If the condition evaluates to true, the loop iterates; if false, execution proceeds to the next statement following the loop.

Syntax

Execution Mechanics

  1. Unconditional Execution: The instruction pointer enters the do block and executes all statements sequentially. This occurs before any condition check.
  2. Condition Evaluation: After the block executes, the boolean condition within the while clause is evaluated.
  3. Branching:
    • If the condition evaluates to true, the instruction pointer jumps back to the start of the do block for the next iteration.
    • If the condition evaluates to false, the loop terminates, and control flow passes to the subsequent program statement.

Variable Scoping

A distinct feature of Kotlin’s do-while loop, contrasting with several other C-family languages, is its scoping rule. Variables declared locally within the do block remain in lexical scope and are fully accessible within the while condition evaluation.

Structural Jump Expressions

The do-while loop supports Kotlin’s structural jump expressions to alter control flow during an iteration. These jumps can be unlabelled (affecting the innermost enclosing loop) or labelled (affecting a specifically designated loop).
  • break: Immediately terminates the innermost loop entirely, bypassing the while condition check, and transfers control to the statement following the loop.
  • continue: Immediately halts the current iteration within the do block and jumps directly to the while condition evaluation of the innermost loop to determine if the next iteration should commence.
  • break@label: Immediately terminates the specific loop marked with the matching label.
  • continue@label: Immediately halts the current iteration and jumps to the while condition evaluation of the specific loop marked with the matching label.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More