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?