Version 3 of Dereferencing

Updated 2002-11-14 18:45:41

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 ipp]]]"

The C asterisks correlate to set calls in derefencing, while in Tcl similar markup is not needed in declaring.

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.)


Category Concept | Arts and crafts of Tcl-Tk programming