endforeach: Shall restore iterator variable in all aspects
First I didn't understand why !6085 (merged) is necessary and has an effect.
To my experience endforeach()
automatically restores the previous value for the iterator variables of the loop.
But now I understand that the state of being undefined is not restored. Instead it will be initialized with an empty value. This was unexpected for me.
Shouldn't this behavior be changed to restore the variable as it was before in all aspects? This would be more consistent to the behavior of restoring the previous value. And it would be consistent to the behavior for iterating over an empty list, in that case the variable is already left undefined.
Example code
cmake_minimum_required(VERSION 3.19)
foreach(v IN ITEMS a)
endforeach()
if(DEFINED v)
message(STATUS "Variable v is defined: '${v}'")
else()
message(STATUS "Variable v is NOT defined")
endif()
set(v "PreviousContent")
foreach(v IN ITEMS a)
endforeach()
if(NOT v STREQUAL "PreviousContent")
message(FATAL_ERROR "Variable v has been modified")
endif()
results in:
-- Variable v is defined: ''
instead of:
-- Variable v is NOT defined
Regardless if this issue is accepted or rejected: the documentation should be updated. I did not find a description what happens with the iterator variable after the loop. Potential docu chapters:
- foreach
- endforeach
- cmake-language / Loops
- cmake-language / Variable as new "Foreach scope"