Home > Enterprise >  Why doesn't pointer need type casting when passing it to a function with constant pointer type
Why doesn't pointer need type casting when passing it to a function with constant pointer type

Time:06-10

I initialize a char[] array with a "hello" string:

char str[] = "hello";
func(str);

Now, the char[] array is passed to a function, taking a const char* pointer parameter:

void func(const char* str)
{
    puts(str);
}

Output:

hello 

Why don't I need to typecast the char[] array to a const char* pointer?

CodePudding user response:

Why I don't need to type cast the char type pointer to const char type pointer?

Because of the implicit qualification conversion. In particular, a pointer to a nonconst type can be converted to a pointer to the corresponding const type.

This can be seen from implicit conversion:

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;

    ...

(emphasis mine)

For example,

int i = 0;
const int *p = &i; // conversion to const happens here

CodePudding user response:

A conversion from a pointer to a non-const can be freely converted to a pointer to a const type. Doing so doesn't change the pointed-to type, but simply adds restrictions to how the pointed-to type is used.

For example:

char str[] = "test";
str[0] = 'p';   // OK
const char *p = str;
p[0] = 't';     // ERROR: pointed-to type is const

This applies to all type qualifiers, which includes restrict and volatile.

Section 6.3.2.3p2 of the C standard spells this out:

For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type; the values stored in the original and converted pointers shall compare equal.

  • Related