-
Notifications
You must be signed in to change notification settings - Fork 128
const, constexpr correctness
-
Always use const or constexpr (compile-time const). Const/constexpr makes the code more clear to the developers, compilers, and users, as they express behavior and intention.
-
Constant variables: read-only, value is not expected to change during the scope of the variable and must be assigned at creation.
-
Don't
const double height; double weight = 180.5; std::string arg0( argv[0] );
-
Do
const double height = 12 * feet + inches; constexpr double weight = 180.5; const std::string arg0( argv[0] );
-
Don't
-
Constant class member variables: must be defined in all constructors, C++11 allows default values defined in the class declaration in *.h
-
Const keyword in functions: use const in class member functions that don't change the state of an object it belongs to or its members.
const
is always assigned after the function arguments, never useconst
for the returning type of any (member and non-member) function (before function name and arguments). It is meaningless asconst
is established when calling that function.-
Don't
class Foo { //issues compiler warnings const double GetHeight( );
-
Do
class Foo { //GetHeight doesn't modify class members double GetHeight( ) const; ... const double height = myFoo.GetHeight();
-
-
Constant function arguments: use
const
if the state of the argument is not changed inside that function. This is independent if the passed variable is non-const.
-
Example for WriteFoo declaration:
double foo = GetFoo( ); WriteFoo( foo );
-
Don't
void WriteFoo( double foo );
-
Do
void WriteFoo( const double foo );
-