Initialize empty list

What is the most idiomatic way to initialize an empty list? I have earlier used

set(mylist)

This works, when I later starts to append items to the list. But I recently understood that this actually “unset” the variable. So I wonder if there is an idiomatically better way to initialize an empty list? Is setting it to an empty string better?

I have also noted in other circumstances that a list with just one element that is the empty string, somehow “collapses” into an empty list. If I for example:

  • start with a list with three elements, the middle being an empty string ( “foo;;bar” )
  • if I pop the last element, the length drops to 2
  • if I now pop the first element, the length drops to 0 (not 1)

I guess having empty elements of a list is not common, so this is not a big “problem”. But it still feels irregular, and non-obvious.

Regards,
Johan Holmberg

Since a list is represented as a string, an empty list is an empty string:

set(mylist "")

If you want to be absolutely sure that the variable will evaluate to an empty list (or empty string), use set(mylist ""). The reason is that unsetting a regular variable can unmask a cache variable of the same name. The following shows how this can happen:

set(MyVar "Hi" CACHE STRING "" FORCE)
message("MyVar = ${MyVar}")

set(MyVar "Barry")
message("MyVar = ${MyVar}")

set(MyVar)
message("MyVar = ${MyVar}")

set(MyVar "")
message("MyVar = ${MyVar}")

When part of a project’s CMakeLists.txt file, the above would print the following:

MyVar = Hi
MyVar = Barry
MyVar = Hi
MyVar = 

Note how using set(MyVar) unset the non-cache variable and re-exposed the cache variable of the same name again. Only after explicitly setting MyVar to an empty string did we manage to ensure ${MyVar} evaluates to an empty value.

2 Likes