No++

No++

Just another blog on C++, GFX and other stuff

04 Oct 2017

Don't fear the constness

I’ve recently realized that, for most C++ beginners, it’s not they don’t want to use the const keyword, they just don’t know how to use it.

What const means

Everything that is specified as const is a implicit contract between you and the compiler. You guarantee that once assigned, you won’t modify the variable that is specified as const.

Moreover the compiler will raise an error during compilation if you try to break this contract (i.e.: trying to modify the value of a const variable).

How const keyword works

First, there is the generic rule:

const applies to anything in front of it (i.e.: on the left side of it).

int const p = 0; // constant integer value
int* const q;    // constant address of an integer value
int const* r;    // address of a constant integer value
int const& s;    // reference of a constant integer value

It works the same way for function class by guaranteeing the function will act as a constant on the class (i.e.: it won’t modify the content of the current instance of the class).

class A
{
public:
  float getValue() const // constant function
  {
    return _v;
  }
private:
  float _v = 0.0f;
};

Then things go messy

But there is an exception in the generic rule. What happen if there is nothing in front of const?

Then in this case, the element immediately following (i.e.: on the right side) will be specified as const. And then again, the confusion can start for beginners who are learning C++ …

Here are some couples of code lines which translate exactly the same by the compiler.

const int n = 0;
int const n = 0;

char const* convertString(std::string const& value);
const char* convertString(const std::string& value);

struct A
{
  const int& computeValue(const float* const array) const;
  int const& computeValue(float const* const array) const;
};

Conclusion

const int n = 0;

int const n = 0;

Always use the generic rule in your code, never use the exception:

  • your brain will like it as you won’t have to make the left-right-side switch everytime your eyes will encounter the const keyword.
  • variable/function declarations will always read fluently from right to left.
  • as a beginner learning C++, you will have only one rule to remember and only one place to put the const keyword to do what you want to do …