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

59 Views Asked by At

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.

2

There are 2 best solutions below

2
Schelte Bron On BEST ANSWER

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.

0
Kevan Riley On

Also, you want:

set a ""

or

set a {}

not

set a []

The latter is an attempt to execute code, that is what '[' ...']' means in Tcl.