C++ – Why Avoid Using `const` in Simple Functions

c++constantsparameter-passing

When learning C++, one of the first functions one gets for learning the concept of a function is something like

int add(int a, int b)
{
    return a+b;
}

Now I was wondering: Should I use the const-keyword here, or rather not, resulting in

int add(const int a, const int b)
{
    return a+b;
}

But would that make sense? Would it speed my program up, do some other important stuff, or just increase confusion?

Best Answer

From the caller's perspective, both the first and the second form are the same.

Since the integers are passed by value, even if the function modifies a and b, the modified values are copies of the original and won't be visible to the caller.

However, from the function implementer's perspective there's a difference. In fact, in the second form:

int add(const int a, const int b)

you will get a compiler error if you try to modify the values of a and b inside the function's body, as they are marked as const.

Instead, you can change those values if you omit the const.
Again, those modifications will not be visible to the caller.

Related Question