1

Messing with some legacy C libraries which use raw pointers I found this to be interesting:

// test.hpp

namespace test
{
    void foo(int const* arg);
}
// test.cpp

#include "test.hpp"

void test::foo(int* arg)
{
    // implementation...
}

Obviously, this won't compile, because void foo(int*) was not declared anywhere in namespace test.

But what about this?

// test.hpp

namespace test
{
    void foo(int* const arg);
}
// test.cpp

#include "test.hpp"

void test::foo(int* arg)
{
    arg = nullptr;
}

This successfully compiles with GCC 12.1.0.

But why is that? In the declaration of foo() in test.hpp we say that arg is a constant pointer which can not be modified. Thus, void foo(int* const) and void foo(int*) should technically be the prototypes of two different functions. Why does the compiler consider them to be the same?

Note, this is not a question about the difference between constant pointer and pointer to a constant. The question is about the logic of the compiler - why does it consider two functions to be the same when they are technically not?

Alexey104
  • 969
  • 1
  • 5
  • 17
  • 1
    Reminder, there are 4 types of pointers: 1) mutable pointer to mutable data; 2) constant pointer to mutable data; 3) constant pointer to constant data; and 4) mutable pointer to constant data. When a *pointer* is constant, the pointer can't be modified. A pointer an point to constant data (read only) or it can point to mutable data (read / write). – Thomas Matthews Jul 21 '22 at 16:49
  • 2
    Forget about pointers here, it's a red herring. Consider `void f(int x);` and `void f(const int x);`. From the _caller_ point of view, they will take the exact same arguments. Sure, in the actual implementations, only one of these can modify the local copy `x`, but that's invisible to the caller. Since they are equivalent for the caller, they offer the same "interface", hence C++ will ignore the "const-ness" in the prototype when it directly refers to the argument (but not in the other cases, as in `void f(const T &x); void f(const T *x); etc.`). – chi Jul 21 '22 at 17:24

0 Answers0