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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With