Skip to content

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.

  1. 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] ) };
  2. Class member variables: must be known at creation time. They disable empty constructors unless a default value is specified.
  3. Class member functions after arguments: don't change the state of an Object or its members
  4. 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();
        
  5. 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 );