I have following piece of code:
typedef uint8_t array_t[8];
static array_t _my_array;
static const array_t * foo(void) {
return &_my_array; // <-- return from incompatible pointer type
}
how do I fix this error? what am I doing wrong?
do I have to cast _my_array as (const array_t *)? Shouldn’t cast from pointer to const pointer be implicit?
Note:
return _my_array;
works as well, i.e. compiles with the same warning.
The problem is the
const; the function returnsconst array_t *(pointer to const array_t), but the returned expression,&_my_array, is of typearray_t *, and the two types are not compatible.The simplest fix is to drop the
constfrom the return type:EDIT:
I’m hesitant to suggest a compiler bug, but I’ve come up with a test program that I think indicates either a bug in gcc or a very obscure aspect of the C standard.
When I compile this with
gcc -c -std=c99 -pedantic-errors c.c(gcc 4.5.2), I get:Why does it complain about an implicit conversion from
that_type*toconst that_type*, but not about a conversion fromthis_type*toconst this_type*.Since
that_typeis a typedef, it’s an alias for an array type, andthat_type*is a pointer to an array (not a pointer to an element of an array); there is no array-to-pointer conversion as far as I can tell. I don’t think the fact thatthis_typeis an integer type andthat_typeis an array type should make any difference.Another data point: on Solaris 9,
cc -c -Xc c.cdoesn’t complain.Logically, converting a pointer to foo to a pointer to const foo should be safe; it doesn’t produce any opportunity to violate const-correctness.
If I’m right, then the code in the question is valid, gcc’s warning is incorrect, and you can work around it either by dropping the
conston the function definition (make it returnarray_t*rather thanconst array_t*, or by adding a cast on the return statement:If I’m wrong, I expect someone will point it out soon.
(My use of
this, a C++ keyword, as an identifier is somewhat deliberate. This is a C question. I understand that C++ has slightly different rules in this area.)EDIT2:
I’ve just submitted a gcc bug report.
EDIT3:
Joseph S. Myers responded to my bug report: