Is it a good style to always use static const rather than #define in C++ O.O. programming?
This is a discussion on static const VS #define within the C++ Programming forums, part of the General Programming Boards category; Is it a good style to always use static const rather than #define in C++ O.O. programming?...
Is it a good style to always use static const rather than #define in C++ O.O. programming?
You don't need "static" const either. But it's a good thing to use const wherever possible rather than define. Define is C-ish and not type safe. Use it for macros and avoid it for everything else, if you can.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
I suppose it depends on what you're doing it for.
If you just need a simple number remembered and used often, then a static const sounds better than #define.
What's the advantage to use "static const" other than const, especially as a class member variable?
Static simply means there will only be a single instance of it. Well, simplified anyway. If you have a lot of classes, you can make it static, since you won't be needing more than one instance (the number won't change anyway!).
But if it's not used in classes, and it's global, then there's no point. I'd rather make const variables that replaces defines global since they're just values to be read (and probably not read at all, but substituted in the code by the compiler in release mode).
I don't know if there's a disadvantage with const variables to replace define. Since it's const, you're telling the compiler the value won't ever change and it can optimize away the variable and put the real value it contains where it's used instead.
Last edited by Elysia; 12-04-2007 at 11:19 AM.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialise this const member variable in the initialisation list).
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way