#arduino #beginner #game #qt #qt3d #rendering

Don't fear the constness

4 May 2017 - #beginner

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
    float getValue() const \\ constant function
        return _v;

    float _v;

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;


const int n = 0;

int const n = 0;

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

Don’t be afraid anymore of using the const keyword!

author-logo zeduckmaster
just another senior C++ developper
mastodon-logo framagit-logo rss-symbol

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.