Say I have this example:
char const * const foo( ){ /* which is initialized to const char * const */ return str; }
What is the right way to do it to avoid the compiler warning "type qualifier on return type is meaningless"?
A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether: The value of an object can be changed. The value of an object must always be read from memory rather than from a register. More than one pointer can access a modifiable memory address.
In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a qualified type. For example, const int is a qualified type representing a constant integer, while int is the corresponding unqualified type, simply an integer.
As of 2014 and C11, there are four type qualifiers in standard C: const (C89), volatile (C89), restrict (C99) and _Atomic (C11). The first two of these, const and volatile, are also present in C++ and are the only type qualifiers in C++.
The way you wrote it, it was saying "the returned pointer value is const". But non-class type rvalues are not modifiable (inherited from C), and thus the Standard says non-class type rvalues are never const-qualified (right-most const was ignored even tho specified by you) since the const would be kinda redundant. One doesn't write it - example:
int f(); int main() { f() = 0; } // error anyway! // const redundant. returned expression still has type "int", even though the // function-type of g remains "int const()" (potential confusion!) int const g();
Notice that for the type of "g", the const is significant, but for rvalue expressions generated from type int const
the const is ignored. So the following is an error:
int const f(); int f() { } // different return type but same parameters
There is no way known to me you could observe the "const" other than getting at the type of "g" itself (and passing &f
to a template and deduce its type, for example). Finally notice that "char const" and "const char" signify the same type. I recommend you to settle with one notion and using that throughout the code.
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