C++ fun with typedef and const

UPDATE. Well actually my previous assumption is wrong and the problem occurs because one type is pointer const vs other pointer data const.

I stumbled on some interesting problem today:

typedef char *MY_KEY;
 
void foo (const MY_KEY key)
{
// ...
}
 
int main (...)
{
 
const char *str = "some str";
foo (str);  // error: smth like unable to convert LPCSTR (const char*) to char*
 
}

Weird isn’t it? From first glance everything looks alright and I really didn’t understood why it was not working. After some googling I find out what is going on. Problem is that qualifier (const or others) applies at the very top level, in my situation once I typedef type with pointer qualifier can not be injected between type and a pointer. Here what is happening:

typedef char *MY_KEY;
void foo (const MY_KEY key) -> equals to -> void foo (const (char *) key)

Now to avoid this situation typedef should be done without pointer, like this:

typedef char MY_KEY;
 
void foo (const MY_KEY *key)
{
// ...
}
 
int main (...)
{
 
const char *str = "some str";
foo (str);  // and it works as it should
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *