Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GCC warning on const qualifier correct?

Tags:

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?

like image 839
Eric Postpischil Avatar asked Feb 03 '19 21:02

Eric Postpischil


People also ask

How does GCC treat warning errors?

The warning is emitted only with --coverage enabled. By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. Suppress warning messages emitted by #warning directives.

How to suppress warnings GCC?

To answer your question about disabling specific warnings in GCC, you can enable specific warnings in GCC with -Wxxxx and disable them with -Wno-xxxx. From the GCC Warning Options: You can request many specific warnings with options beginning -W , for example -Wimplicit to request warnings on implicit declarations.


1 Answers

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.

like image 106
Eric Postpischil Avatar answered Sep 19 '22 06:09

Eric Postpischil