Control structures should have complete curly-braced block of code

# T019

# Control structures should have complete curly-braced block of code

Description:

Control structures managed by for, if and while constructs can be associated with a single instruction or with a complex block of code. Standardizing on the curly-braced blocks in all cases allows to avoid common pitfalls and makes the code visually more uniform.

    if (x) foo();     // bad style
    if (x) { foo(); } // OK

    if (x)
        foo();        // again bad style

    if (x)
    {                 // OK
        foo();
    }

    if (x)
        while (y)     // bad style
            foo();    // bad style

    if (x)
    {                 // OK
        while (y)
        {             // OK
            foo();
        }
    }

    for (int i = 0; i = 10; ++i);  // oops!
        cout << "Hello\n";

    for (int i = 0; i = 10; ++i)   // OK
    {
        cout << "Hello\n";
    }

Compliance: Inspirel

Show source code for this rule

Hide source code

    # control structures should have complete curly-braced block of code

    foreach fileName [getSourceFileNames] {

        set state "start"
        foreach token [getTokens $fileName 1 0 -1 -1 {for if while leftparen rightparen leftbrace semicolon}] {
            set type [lindex $token 3]

            if {$state == "control"} {
                if {$type == "leftparen"} {
                    incr parenCount
                } elseif {$type == "rightparen"} {
                    incr parenCount -1
                    if {$parenCount == 0} {
                        set state "expectedblock"
                    }
                }
            } elseif {$state == "expectedblock"} {
                if {$type != "leftbrace"} {
                    set line [lindex $token 1]
                    report $fileName $line "full block {} expected in the control structure"
                }
                set state "block"
            }

            if {$type == "for" || $type == "if" || $type == "while"} {
                set parenCount 0
                set state "control"
            }
        }
    }

Rule index