Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The fallthrough statement in Go is a control flow keyword used exclusively within expression switch statements to override the language’s default implicit break behavior. When encountered, it unconditionally transfers execution to the first statement of the immediately succeeding case or default clause in lexical order, bypassing any condition evaluation for that subsequent clause.
package main

import "fmt"

func main() {
    x := 1
    switch x {
    case 1:
        fmt.Println("Block 1 executed")
        fallthrough
    case 2:
        // This block executes immediately after Block 1, 
        // even though x != 2.
        fmt.Println("Block 2 executed unconditionally")
    default:
        fmt.Println("Default block")
    }
}

Lexical and Syntactic Rules

To compile successfully, the fallthrough statement is subject to strict structural constraints:
  1. Top-Level Terminal Placement: The fallthrough keyword must be the final statement in the top-level statement list of a case or default clause. It cannot be nested inside any inner blocks (such as if, for, or explicit {} scopes) within the clause, nor can it be followed by other statements.
  2. Unconditional Transfer: The transfer of control does not evaluate the expression of the subsequent clause. The runtime simply jumps to the next block’s instruction pointer.
  3. Prohibited in Final Clause: It is a compile-time error to place a fallthrough statement in the lexically final clause of a switch statement, as there is no subsequent block to transfer control to. This applies strictly to the last clause in the switch body, regardless of whether it is a case or default clause. If a default clause is placed above other cases, it is perfectly valid to use fallthrough at the end of it.
  4. Prohibited in Type Switches: The fallthrough keyword cannot be used within a type switch (switch v := x.(type)). It is only valid in expression switches.

Execution Flow Example

package main

import "fmt"

func main() {
    x := 10

    switch x {
    case 10:
        x--
        fallthrough // Transfers control to the next case
    case 99:
        x--         // Executes despite x being 9, not 99
        fallthrough // Transfers control to the default block
    default:
        x--
    }
    
    fmt.Println(x) // Output: 7
}
In the execution above, the condition case 99: is entirely ignored by the runtime due to the preceding fallthrough. The execution pointer cascades downward sequentially until it hits a clause lacking a fallthrough statement, or until the switch terminates.
Master Go with Deep Grasping Methodology!Learn More