I'm new to tcl
, and would like to get some understanding of how return
statements work in the language. Take the following code, for instance:
proc add name {
set name [expr $name 2]
}
set y 5
puts [add $y]
I was surprised to find that this actually prints the value 7
to my terminal. I was expecting nothing to print out since I have not included a return
statement in my procedure.
When I do include a return statement, it seems to override this strange default behavior:
proc add name {
set name [expr $name 2]
return hello
}
set y 5
puts [add $y]
The above will indeed return hello. But what does it do with the 7
?
Why does the procedure still return a 7
even if I have no return statement? Why does it then override this behavior when I do provide a return statement?
CodePudding user response:
If you don't explicitly return
a value, the value of the last statement executed in the proc will be returned. This is documented at https://www.tcl-lang.org/man/tcl8.6/TclCmd/proc.html at the end of the DESCRIPTION section.