Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between writing static const uint variable and anonymous enum variable?

Tags:

c++

enums

boost

Was looking at boost asio ssl_client.cpp example and found this right on the top:

enum { max_length = 1024 };

Wonder, is there any difference between this and

namespace {
    const int max_length = 1024;
}

or

static const int max_length = 1024;

Or maybe they are absolutely equal but this is just shorter?

like image 558
Victor Polevoy Avatar asked Oct 18 '22 22:10

Victor Polevoy


1 Answers

They're equivalent, if you use it for the value, not by reference.

The enum { constantname = initializer }; idiom used to be very popular in header files, so you could use it within a class declaration without problems:

struct X {
    enum { id = 1 };
};

Because with a static const member, you would need an out-of-class initializer and it couldn't be in the header file.

Update

Cool kids do this these days:

struct X {
    static constexpr int id = 1;
};

Or they go with Scott Meyer¹ and write:

struct X {
    static const int id = 1;
};

// later, in a cpp-file near you:
const int X::id;

int main() {
    int const* v = &X::id; // can use address!
}

¹ see Declaration-only integral static const and constexpr data members, Item #30

like image 166
sehe Avatar answered Nov 15 '22 06:11

sehe