Boost logo

Boost :

From: Gennaro Prota (gennaro_prota_at_[hidden])
Date: 2004-02-02 07:20:01


On Sat, 31 Jan 2004 09:12:58 -0700, "Jonathan Turkanis"
<technews_at_[hidden]> wrote:

>Well, I can't really argue with that.

Maybe that's up to me :) There are really cases where you want the
compiler to count the elements for you (initialization with the [] =
{...} syntax) and retrieve that number *later*.

Incredibly, the first C++ file I opened this morning showed me this
unfairly neglected situation. And it was my code... Please don't
comment on that :)

  unsigned long numbers[] = { 0, 1, 40247 };

  const std::size_t array_count = sizeof(numbers) /
                                  sizeof(numbers[0]);

  for (std::size_t i = 0; i < array_count; ++i) {
    ...
  }

Note the loop over the array elements. The whole code is in a unit
test and each number in the array initializer list corresponds to a
test case of a function. So adding/removing numbers means
adding/removing test cases.

As the code is, I can remove any number from the list without having
to modify anything else. Instead, if you write

  const std::size_t n = 3;
  unsigned long numbers[n] = { 0, 1, 40247 };

and then drop one of the numbers without also fixing the definition of
n you change semantics (the additional element(s) are initialized to
zero) usually with no compiler warning. Basically this is a situation
where you have a list of objects and want to use them all, no matter
how many they are; the fact that you have to count them is an
implementation detail due to the lack of a for-each construct in the
language.

PS: Of course I'm not saying one has to use a template for this; I
guess most people would consider the sizeof/sizeof technique safe
enough (chances that you use a pointer instead of an array are quite
low). But, anyway... :)

Genny.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk