stringtclstring-lengthubuntu-22.04

In Tcl, why is the string length of an empty string 1, not 0?


In tclsh, first make an empty string:

set a []

Then run the following command:

string length a

It returns 1.

I'm expecting a return value of 0 for the length of an empty string, because it is defined to be the number of characters in the string. But I got 1. Why is that? I read this document, but still don't understand. I'm using Tcl 8.6 on Ubuntu 22.04.


Solution

  • To get the value of variable "a" in Tcl, you use $a. When you run a command like string length a, you actually request the length of the literal string "a". The length of that string is 1. To get the length of the string stored in variable "a", you must use string length $a.