const Primitive Data Type

Learn about const primitive data type parameters.

Let’s explore when to use const parameters in the parameter list of function signatures. Let’s differentiate between fundamental types (also known as primitive data types) and class types.

Introduction

This section talks about primitive data types, such as bool, int, float, char, etc.

Should such parameters be taken as const?

The answer is no, because it will be inefficient. We can access these data types with one memory read if passed by value. On the other hand, if we pass them by reference or pointer, the address of the variable will be read, and then by dereferencing it, the value. That’s two memory reads instead of only one.

We should not pass fundamental types by const&.

But should we pass them simply by const?

If we don’t plan to modify the parameter’s values, we could or we should! For better readability, for the compiler, and the future!

void setFoo(const int foo) {
   this->m_foo = foo;
}

It seems pedantic, but it doesn’t hurt. It’s explicit, and we don’t know how the method will grow in the future. Maybe some additional checks will be added done, and even some exception handling.

If the parameter is not marked const, and the value changes, it might cause subtle errors.

If we mark foo const, we will make this scenario impossible.

We will have to remove the const qualifier if we need to change the value of that parameter, but we’ll do it intentionally. That change will stand out in a code review if we keep our pull request short.

On the other hand, if we have to modify the parameter, we will not mark it const.

When not to use const parameters

From time to time, we can see the following pattern.

Don’t make a parameter as const if a copy is needed.

void doSomething(const int foo) {
    // ...
    int foo2 = foo;
    foo2++;
    // ...
 }

There is no reason to take a const value if we plan to modify it. One more variable on the stack in vain, on more assignments without any reason. Simply take it by value.

Parameters non-const for modification

Take value parameters non-const if we plan to modify them.

void doSomething(int foo) {
    // ...
    foo++;
    // ...
}

In short, we don’t take fundamental types by const& or const T*. We only take them by const T when we don’t plan to modify them.

Get hands-on with 1200+ tech skills courses.