Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Array initialization with enum indices in C but not C++ (thegreenplace.net)
5 points by mattyb on Feb 15, 2011 | hide | past | favorite | 1 comment


It is unfortunate that C++ doesn't handle that syntax.

First thing I'll note...a "switch" statement implicitly defines a lookup table, and is probably the best way to handle this kind of problem regardless of what the language allows.

Having said that, to do initialization on the fly in C++, one trick you can do is to write a function. The main downside is that you must add a "()" wherever the "variable" is used, instead of just a variable name.

So to continue their example, you might say:

    enum {
       PL_SIZE = 56
    };
    static const int *price_lookup() {
        static int *_ = NULL;
        if (!_) {
            _ = new int[PL_SIZE];
            _[APPLES] = 6;
            _[ORANGES] = 10;
            _[STRAWBERRIES] = 55;
        }
        return _;
    }
...and then, e.g. instead of price_lookup[i] you'd have to say price_lookup()[i]. Obviously their ARRSIZE() macro no longer works, either, hence the PL_SIZE definition.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: