0

Is it considered secure to write a condition without braces? e.g.:

if [$step > 0] {
# …
}

Or must I use braces? e.g.:

if {[$step > 0]} {
# …
}

The line without the braces looks readable compared to the line with the braces.
But are there any disadvantages/caveats to which I should be aware of?

Dor
  • 7,344
  • 4
  • 32
  • 45

1 Answers1

1

You need the braces. Furthermore, you don't want the []. [] evaluates its contents as a command, and replaces itself with the return value of the command. So your first version

if [$step > 0] { }

assuming $step is 3, is equivalent to

if [3 > 0] { }

which tries to evaluate [3 > 0] as a command and complains that 3 is not a command.

Your second version has the same problem, because the expression evaluates any embedded command substitutions.

What you really want is just

if {$step > 0} { ... }

The thing to remember is that in Tcl, control structures behave the same way as user-defined functions (and in fact, can typically be implemented using Tcl code). The if command takes 2-4 arguments, of the form "if" condition then-block [["else"] else-block]. The first argument is always the condition. The second is the then-block. The third is the optional word "else", followed by the 4th which is an optional else-block (if the "else" word is present, the else-block is required).

Since this construct takes simple arguments, you need to be sure to provide it arguments. So the condition argument needs to be braced, so as to ensure it's a single argument (and also, so as to ensure any substitutions aren't interpreted too soon, as the evaluation of the condition will interpret them for you). Similarly the then-block and else-block are braced.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • Is this answer valid also for the case `if [string match ...] { ... }` ?? – Dor Nov 26 '13 at 18:14
  • @Dor: The short answer is "yes, you should still use braces". But this case is a bit different. In your question, your condition was an expression suitable for passing to `expr` (which is what `if` does). In this case, your expression is a command substitution that returns 0 or 1. The correct thing to do is still use braces, because the `if` will evaluate your command substitution for you, but technically it doesn't matter in this case as evaluating `0` or `1` as an expression returns the same `0` or `1`. But I recommend using braces always for consistency – Lily Ballard Nov 26 '13 at 18:19
  • 2
    Using braces also prevents "double substitution" -- it means the tcl parser doesn't have to substitute variables and commands because the expr parser is going to do that anyway. – glenn jackman Nov 26 '13 at 19:54