[Development] Best practice for defining an integer constant
Tony Van Eerd
tvaneerd at blackberry.com
Fri Feb 14 18:56:15 CET 2014
> >
> > The Qt coding conventions
> > (http://qt-project.org/wiki/Coding-Conventions)
> > recommend using an enum over 'const int'.
> >
> > The rationale given there is that an enum will be replaced at
> > compile-time resulting in 'faster code'. Won't that be the case with
> > 'const int' as well? I think a 'const int' will be inlined in the code. CMIIW.
>
> That is the case, *except* if you pass it via const-ref. If you do that, then ODR
> kicks in and you need to have the variable defined somewhere.
>
> For variables in the file scope, the declaration is the definition, so it's not a
> problem. For variables in a class scope, the static const declaration is
> *not* the definition.
>
One place where const is better, is where you want a type other than int. Like bool. (Often in metafunction templates, the ::value result is either true or false.) Or if you want a specific size of int, since enums (until C++11) don't have a specific size.
Tony
More information about the Development
mailing list