Skip to content

const, constexpr correctness

williamfgc edited this page May 4, 2017 · 6 revisions
  1. 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.

  2. 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] );
  3. Constant class member variables: must be defined in all constructors, C++11 allows default values defined in the class declaration in *.h

  4. 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 use const for the returning type of any (member and non-member) function (before function name and arguments). It is meaningless as const 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();
  5. 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 );