[CMake] foreach(loop_var RANGE total)

Nicolas Desprès nicolas.despres at gmail.com
Mon Sep 15 04:33:13 EDT 2008


On Fri, Sep 12, 2008 at 2:25 PM, David Cole <david.cole at kitware.com> wrote:
> Add this line after the list LENGTH call:
> math(EXPR list_max_index ${list_count}-1)
>

Yes, I tried this work around already, but I don't like it because it
increase the code size and it doesn't work in case of an empty list:

set(list "")
list(LENGTH list list_count)
message(STATUS "${list_count}")
math(EXPR list_max_index ${list_count}-1)
message(STATUS "list_max_index=${list_max_index}")
foreach(i RANGE ${list_max_index})
  message(STATUS "i=${i}")
  list(GET list ${i} x)
  message(STATUS "${i} -> ${x}")
endforeach(i)


Produces:

-- 0
-- list_max_index=-1
-- i=0
CMake Error at /tmp/test.cmake:8 (list):
  list index: 0 out of range (-0, 4294967295)1


So, I have to increase the code even more by checking this case separately.

> and then use list_max_index instead of list_count in the foreach loop.
> The documentation (cmake --help-command foreach) is quite clear that the one
> arg form of the range command loops from 0 to total including total...

Yep, I understood the documentation and I found it quite clear.

What, I'm pointing here is that such a behavior is quite uncommon in
other program languages and not having the strict form is cumbersome
in many cases.

Thanks for your reply,

Nico

>
> HTH,
> David
>
> On Fri, Sep 12, 2008 at 5:56 AM, Nicolas Desprès <nicolas.despres at gmail.com>
> wrote:
>>
>> Hi,
>>
>> I'm using cmake 2.6.0.
>>
>> I'm trying the foreach(loop_var RANGE total) syntax and I find its
>> behavior quiet surprising since it is something equivalent to:
>>
>> for (int loop_var = 0; loop_var <= total; ++loop_var)
>>  ;
>>
>> Most of the time (specially when you iterate over a list) you want to
>> test for 'loop_var < total'.
>>
>> For instance you can't write code like that:
>>
>> list(LENGTH list list_count)
>>
>> foreach(i RANGE ${list_count})
>>
>>    list(GET list ${i} x)
>>
>> endforeach(i)
>>
>> list(GET always fail on the last iteration.
>>
>> Cheers,
>>
>> --
>> Nicolas Desprès
>> _______________________________________________
>> CMake mailing list
>> CMake at cmake.org
>> http://www.cmake.org/mailman/listinfo/cmake
>
>



-- 
Nicolas Desprès


More information about the CMake mailing list