[CMake] foreach: bug or feature?

Marcel Loose loose at astron.nl
Wed Apr 29 07:56:12 EDT 2009


Hi all,

foreach(cnt RANGE 3 1)
  message(STATUS "${cnt}")
endforeach(cnt RANGE 3 1)

produces the output
-- 3
-- 2
-- 1

Apparently, CMake decides to count backward whenever stop > start.

I find this a little counter-intuitive; counting now starts at stop and
stops at start (confusing isn't it). Why not let the third optional
parameter step denote the fact that I want to count down. This requires
that step can have a negative value, which currently isn't allowed.

My suggestion would be:
1) Always start counting at start and stop counting at stop. This
implies that if start > stop, the loop will not be executed at all.
2) Let step determine the increment that is applied to cnt with each
iteration. Variable step may be negative; in that case, the net effect
is that cnt is decremented with each iteration, and the loop is only
executed if start > stop.

So, for example:

foreach(cnt RANGE 3 1 -1)
  message(STATUS "${cnt}")
endforeach(cnt 3 1 -1)

would then produce the output
-- 3
-- 2
-- 1

B.T.W.: Is there a reason for counting up to and including stop, instead
of the more usual up to?

Kind regards,
Marcel Loose.




More information about the CMake mailing list