Version 7 of Dereferencing

Updated 2002-11-25 17:34:26

Richard Suchenwirth 2002-11-14 - A reference is something that refers, or points, to another something (if you pardon the scientific expression). In C, references are done with *pointers* (memory addresses); in Tcl, references are strings (everything is a string), namely names of variables, which via a hash table can be resolved (dereferenced) to the "other something" they point to:

 puts foo       ;# just the string foo
 puts $foo      ;# dereference variable with name of foo
 puts [set foo] ;# the same

This can be done more than one time with nested set commands. Compare the following C and Tcl programs, that do the same (trivial) job, and exhibit remarkable similarity:

 #include <stdio.h>
 int main(void) {
   int    i =      42;
   int *  ip =     &i;
   int ** ipp =   &ip;
   int ***ippp = &ipp;
   printf("hello, %d\n", ***ippp);
   return 0;
 }

...and Tcl:

 set i    42
 set ip   i
 set ipp  ip
 set ippp ipp
 puts "hello, [set [set [set [set ippp]]]]"

The C asterisks correlate to set calls in derefencing, while in Tcl similar markup is not needed in declaring. But why four sets for three asterisks? Because also the first mention of i in c is a dereference, to pass its value into printf; Tcl makes all four of them explicit (otherwise, you'd see hello, i). One dereference is so frequent that it is typically abbreviated with $varname, e.g.

 puts "hello, [set [set [set $ippp]]]"

has set where C uses asterisks, and $ for the last (default) dereference.

The hashtable for variable names is either global, for code evaluated in that scope, or local to a proc. You can still "import" references to variables in scopes that are "higher" in the call stack, with the upvar and global commands. (The latter being automatic in C, given the names are unique; else, the innermost scope wins).

(This little piece was written to defuse the superstition that Tcl has no references, or needs more of the same. See also Pass by reference, which is also called "call by name", pretty exactly describes how Tcl implements it...)


One visitor to the Tcl chatroom wondered why

 expr $$item

turns the value of a variable whose name is in item from 530E001 to 5300.0 - what happens is that the Tcl parser does a first derefencing, e.g., if item has the value ID:

 * expr $ID

and expr does a second dereferencing (or substitution). Not much arithmetics to do on its input, but at least you get it back in canonical double representation...


Category Concept | Arts and crafts of Tcl-Tk programming