Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a type qualifier on a return type meaningless?

Tags:

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"?

like image 356
vehomzzz Avatar asked Oct 22 '09 13:10

vehomzzz


People also ask

What is the use of type qualifier?

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.

What is the use of type qualifiers in C?

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.

What are qualifiers types of qualifiers?

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++.


1 Answers

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.

like image 77
Johannes Schaub - litb Avatar answered Sep 30 '22 18:09

Johannes Schaub - litb