The buggy const

In C/C++, there are constants and pointer to constants. I’m talking here about constants (i.e., const int var1; int* const var2) and not pointer to constants (i.e., const int* var3).

In 90% of cases that I see, usage of constants for local “variables” and parameters is “wrong”. People seems to use it for a variable that is not changing, while, in my opinion, it should rather be used for variables that should never change.

Anyway, I always thought that constant parameters were not part of function signatures, because a const parameter has nothing to do with the caller, but is routine implementation detail. Indeed, this code compiles, links and run with G++ and MSVC++ and is also validated by the Comeau online validator:

#include <stdio.h>

class Test
{
public:
    void m1(const int n);
    void m2(int n);
};

int main()
{
    Test t;
    t.m1(10);
    t.m2(10);
    return 0;
}

void Test::m1(int n)
{
    printf("%d\n", n);
}

void Test::m2(const int n)
{
    printf("%d\n", n);
}

But not all compilers agree. It has been sent some patches fixing these inconsistencies to compile Firebird with Solaris Sun Studio compiler. This usage seems to cause problems because the compiler treat the declaration and implementation as different signatures.

In Java, final could be used for the same thing. Let see what it think about:

interface Int
{
    public void m1(final int n);
    public void m2(int n);
}

class Test implements Int
{
    public void m1(int n)
    {
    }

    public void m2(final int n)
    {
    }
}

Java also accepts this code.