Eric Postpischil
Eric Postpischil

Reputation: 222744

Is GCC warning on const qualifier correct?

Consider the follow code, which arose from this question:

const int (*foo(const char *a))[1]
    { return (const int (*)[1]) a; }

When compiled with GCC 8.2 (and older versions) using -Wcast-qual, GCC warns:

source>:2:15: warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual]
      { return (const int (*)[1]) a; }
               ^

Is this warning correct? Clearly the destination type has a const qualifier in it.

It is on the element type rather than on the thing immediately pointed to by the pointer, which is the array type. However, the warning remains even if we use typedef int T[1]; and replace the cast with (const T *). Additionally, per C 2018 6.7.3 10, qualifiers on an array type apply to the element type, not the array type, so the type is the same either way.

Clang does not show this warning.

If we change the cast to (const void *):

const int (*foo(const char *a))[1]
    { return (const void *) a; }

then the warning vanishes. If we add -pedantic to the compilation switches, we get a different warning about const:

source>:2:15: warning: return discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
      { return (const void *) a; }
               ^~~~~~~~~~~~~~~~

This looks like the same warning except it is about the implied conversion from the return expression to the function return type, whereas the previous warning was about the explicit conversion in the cast. But this one appears only with -pedantic. Why?

Upvotes: 6

Views: 818

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222744

This is GCC bug 81631. GCC fails to recognize the cast to a pointer to an array retains the const qualifier, due to complications with qualifiers applied to an array actually applying to the array elements.

Upvotes: 5

Related Questions