Interesting behavior about condition statement in TCL

Viewed 66

This might be a silly question. But I just found one confusing thing in TCL.

Below is an example code.

set x test_string

if {$x==y} {
    puts "Matching!"
} else {
    puts "Not matching."
}

if {$x==z} {
    puts "Matching!"
} else {
    puts "Not matching."
}

When I run this code, it ends up with below error.

invalid bareword "z"
in expression "$x==z";
should be "$z" or "{z}" or "z(...)" or ...
    (parsing expression "$x==z")
    invoked from within
"if {$x==z} {
        puts "Matching!"
} else {
        puts "Not matching."
}"
    (file "test.tcl" line 3)

I'm aware that when we do comparison with string, the string should be quoted. So the following makes more sense.

if {$x=="y"} {
    puts "Matching!"
} else {
    puts "Not matching."
}

if {$x=="z"} {
    puts "Matching!"
} else {
    puts "Not matching."
}

But what makes me curious is, it seems the character y doesn't cause such error.

Could anybody please give some explanation about this? I cannot tell if there's anything special about this y here.

Thanks!

1 Answers

Because boolean values don't have to be quoted.

% expr true
true
% expr false
false
% expr not_a_boolean
invalid bareword "not_a_boolean"
...

See the Tcl_GetBoolean man page:

Tcl_GetBoolean expects src to specify a boolean value. If src is any of 0, false, no, or off, then Tcl_GetBoolean stores a zero value at *boolPtr. If src is any of 1, true, yes, or on, then 1 is stored at *boolPtr. Any of these values may be abbreviated, and upper-case spellings are also acceptable.

y is the unambiguous abbreviation of yes, a true value

Related