Question

I recently found out that you can add and remove cv-qualifier from value arguments in a function declaration and it's implementation. For instance:

F.h

f(const int i);

F.cpp

f(int i) { i++; }

test.cpp

#include "F.h"
f(0);

The f(int i) implementation will be called. Since its a copy by value, I see no problems with the code compiling. But can anyone imagine a case, where it's somehow useful to add the const to the declaration as done above? Why is it possible at all? Maybe someone can give a more useful application?

Was it helpful?

Solution

Top-level CV qualifiers on function arguments are ignored, i.e. they are not part of the function signature. Rather, if you will, they are part of the implementation of the function, since they qualify the local variables corresponding to the formal function parameters. Therefore, if it pleases you, you may qualify function parameters in the function definition:

int power(int val, int n, int base);

int power(int val, int n, const int base)
{
    while (n --> 0) val *= base;
    return val;
}

Some people find it offensive if the definition has different-looking function parameters from the declaration, though. It's a matter of taste and style. The benefits of qualifying the arguments are probably small, though there is some value for the implementation in documenting that you don't plan to change a variable.

OTHER TIPS

Some people like to state in their definition that they are not going to change a parameter even though it is only visible locally. For example:

void f(int);
void f(int const);

void f(int const x) {
    x = 3; // ERROR!
}

The definition is the function which was just declared, i.e., there is no change on the signature (well, unless you happen to use Sun's CC which actually takes the const into account for the mangled name but that's just an error). All three signatures declare exactly the same function and the const only affects the body of the definition if it is used in the definition's declaration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top