made_in_india
made_in_india

Reputation: 2279

Expecting an error in TCL for the code for non initialization of variable

I have the below small code I am expecting the TCL interpreter to throw error for the variable not initialized but it not throwing an error

set v1 "test" 
if { ($v1 != "test") && ($v2 == "3") } { 
  puts "fun" 
} 
#v2 is not initialized   

No error is being thrown by interpreter for v2 , as it not initialized

Upvotes: 1

Views: 172

Answers (1)

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

First, the sublanguage of expr in TCL, (which is also used in if, while, for) works in another way than TCL itself. In this sublanguage, $ doesn't mean variable substitution, but a variable reference. Variables are accessed when their containing subexpressions are evaluated. And logical operations are short-circuiting, evaluating operands from left to right until the result is known, as in C language.

That's why $v2 == 3 is not evaluated in your example, and nonexistent $v2 is not an error. This behavior is commonly used with code like this:

if {[info exists myvar] && $myvar} { .... }

Upvotes: 5

Related Questions