-
Notifications
You must be signed in to change notification settings - Fork 128
const, constexpr correctness
williamfgc edited this page May 1, 2017
·
6 revisions
Always use const or constexpr (compile-time const) when possible. Const/constexpr to the compiler and makes the code more clear to the developers as they express behavior and intention.
- Variables: read-only, value is not expected to change during the scope of the variable and must be defined.
-
Don't
const double height;
double weight = 180.5; // use constexpr double weight = 180.5;
std::string arg0 = std::string ( argv[0] );
-
Do
const double height = 12 * feet + inches;
constexpr double weight = 180.5;
const std::string arg0{ std::string ( argv[0] ) };
-
- Class member variables: must be known at creation time. They disable empty constructors unless a default value is specified.
- Class member functions after arguments: don't change the state of an Object or its members
- Do not use const in the returning type of a function. It is meaningless as const is established when calling that function.
-
Don't
const double GetHeight( );
-
Do
double GetHeight( ); ... const double height = GetHeight();
-
- Use const in function arguments passed by value or references if the state of the argument is not changed inside that function. It doesn't matter if the original variable is non-const.
-
Example:
double foo = F(); WriteFoo( foo ); // from WriteFoo( const double foo ); not WriteFoo( double foo );
-