1
#include <iostream>
int foo(const char* keke) {
  std::cout << keke;
  return 0;
}
int main()
{
  char* keke = new char(10);
  char* const haha = keke;
  return foo(haha);
}

Why there is no any errors/warning while compiling the above code?

The type of haha is char* const, while foo only receive argument of type const char*. Could char* const implicit convert to const char*?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Jichao
  • 40,341
  • 47
  • 125
  • 198

1 Answers1

4

Yes. It's called qualification conversions (one of the implicit conversions):

(emphasis mine)

A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).

"More" cv-qualified means that

a pointer to unqualified type can be converted to a pointer to const;
...

It means char* could be implicitly converted to const char*.

const qualifier on the pointer itself doesn't matter here, the parameter keke itself is declared to be passed by value, it's fine the argument to be copied from haha (i.e. the const pointer; char* const).

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • is there any implict conversion involved in the function call?`it's fine` in `passed by value`... – Jichao Aug 19 '16 at 04:45
  • @Jichao You meant from `char* const` to `char*`? No. – songyuanyao Aug 19 '16 at 05:29
  • In function call, there is no need to do type match for `char* const` and `char *`? – Jichao Aug 19 '16 at 08:01
  • 1
    @Jichao Think about `const int ci = 1; int i = ci;`, they're the same case. – songyuanyao Aug 19 '16 at 08:04
  • 1
    @Jichao IMO we don't say conversion for this, we say assignment, like it's fine to assign `char*` to `char* const`, or assign `char* const` to `char*`, – songyuanyao Aug 19 '16 at 08:24
  • Is there any reference for such circumstances. Why does the constness for non-pointer-type and pointer type behave difference? – Jichao Aug 19 '16 at 08:27
  • @Jichao Because they're totally different thing. You might want to read [this](http://stackoverflow.com/q/1143262/3309790). – songyuanyao Aug 19 '16 at 08:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121323/discussion-between-jichao-and-songyuanyao). – Jichao Aug 19 '16 at 08:36