A.7   Code Layout

The maximum length for any line of code is 80 characters. If more than 80 characters are required, use the backslash character to continue on the next line.

The rest of this section describes conventions for the graphic layout of Tcl code, covering the following elements:

Vertical Spacing

  • A for statement where the initial, conditional, and loop statements can be written on a single line:

for {set i 0} {$i < 10} {incr i 3} {

  • A switch statement whose actions are short and nearly identical (see the switch statement format in Indentation).

The if statement is not an exception. The conditionally executed statement always goes on a separate line from the conditional expression:

if {$i > $count} { 
    set i $count 
}

Horizontal Spacing

set status [fooGet $foo [expr $i + 3] $value] 
if {&value & &mask} {

set a [expr ($b + $c) * \ 
            ($d + $e)] 
set status [fooList $foo $a $b $c \ 
                    $d $e] 
if {($a == $b) && \ 
    ($c == $d)} { 
    ... 
}

Indentation

while { condition }{ 
    statements 
} 
 
foreach i $elem { 
    statements 
}

  • procedure declarations
  • conditionals (see below)
  • looping constructs
  • switch statements
  • switch patterns

if { condition } { 
    statements 
} else { 
    statements 
}
The form of the conditional statement with an elseif is:

if { condition } { 
    statements 
} elseif { condition } { 
    statements 
} else { 
    statements 
}

switch [flags] value { 
    a   { 
        statements 
        } 
    b   { 
        statements 
        } 
    default { 
        statements 
        } 
}
If the actions are very short and nearly identical in all cases, an alternate form of the switch statement is acceptable:

switch [flags] value { 
    a   {set x $aVar} 
    b   {set x $bVar} 
    c   {set x $cVar} 
}

Comments

  • Begin single-line comments with the pound symbol as in the following:

# This is the correct format for a single-line comment 
 
set foo 0

  • Multi-line comments have each line beginning with the pound symbol as in the example below. Do not use a backslash to continue a comment across lines.

# This is the CORRECT format for a multiline comment 
# in a section of code. 
 
set foo 0 
 
# This is the INCORRECT format for a multiline comment \ 
in a section of code. 
 
set foo 0

set day    night    ;# This is a global variable