Question

I have many classes in the system that I'm currently developing and in these classes I have an array about the "name" of something. The name should be at most 30 characters.

Initially I used just 10 characters but now I need to increase the limit. Increasing the limit takes time though because I use this kind of array in many places. It would be easier if I used #define NAME_SIZE 30 or something like that and then all I would have to do is change one number instead of around twenty.

However I'm not sure if that's a "legal" thing to do in C++.

It would save me tons of time in the future, that's why I'm asking.

Was it helpful?

Solution

Yes, there is nothing technically wrong with it, except that #define is usually inferior to a const std::size_t MAX_NAME_SIZE = 30; Even better would be to have a dynamic size, e.g. using std::string.

Scott Meyers has an interesting column about systems that use gratuitous fixed sizes, called The Keyhole Problem

The Keyhole Problem arises every time software artificially restricts something you want to see or something you want to express. If you want to see an image, but your image-viewing software artificially restricts how much of that image you can see at a time, that’s the keyhole problem. If you want to specify a password of a particular length, but your software says it’s too long, that’s the keyhole problem. If you want to type in your U.S. telephone number, but your software refuses to let you punctuate it in the conventional manner with a dash between the three-digit prefix and the four-digit exchange, that’s the keyhole problem.

Apart from annoynance from users, you also open your systems to all sorts of security issues (e.g. buffer overflow exploits).

OTHER TIPS

Yes, it's legal. But it's generally preferable to use actual constants instead of macros:

const int max = 30;
char blah[max];

Another alternative is to use a std::string and not have an hard-coded limit (following the zero-one-infinity rule).

Yes, this is legal, but you might want to use a const int NAME_SIZE = 30;. This can be safely put in a header file. Unlike non-const global variables, having const variables in different translation units (cpp files) creates no problems for linker, since each constant is local to a file it's defined in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top