Why does the type specifier by return type not make sense?

Let's say I have this example:

char const * const foo( ){ /* which is initialized to const char * const */ return str; } 

What is the correct way to do this to avoid a compiler warning? Does the classifier type by return type make no sense?

+19
c ++ c
Oct 22 '09 at 13:27
source share
3 answers

As you wrote it, he said that the value of the returned pointer is const. But the values โ€‹โ€‹of the non-class class do not change (inherited from C), and thus the standard says that the values โ€‹โ€‹of the non-class class are never const-qual (the rightmost const was ignored even by the one you specified), since const will be a little redundant, do not write it - for 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(); 

Note that for type "g" the constant is significant, but for rvalue expressions generated from type int const , const is ignored. So the following error:

  int const f(); int f() { } // different return type but same parameters 

I do not know that you could observe "const", except to get the type "g" (and pass &f to the template and print its type, for example). Finally, note that โ€œchar constโ€ and โ€œconst charโ€ mean the same type. I recommend that you deal with one concept and use it throughout the code.

+21
Oct 22 '09 at 13:31
source share

In C, since the return values โ€‹โ€‹of the function and the qualification values โ€‹โ€‹do not make sense.
In C ++ this may be different, check out the other answers.

 const int i = (const int)42; /* meaningless, the 42 is never gonna change */ int const foo(void); /* meaningless, the value returned from foo is never gonna change */ 

Only objects can be meaningfully qualified.

 const int *ip = (const int *)&errno; /* ok, `ip` points to an object qualified with `const` */ const char *foo(void); /* ok, `foo()` returns a pointer to a qualified object */ 
+4
Oct 22 '09 at 13:42
source share

None of the previous answers answer the question "the right way to do this."

I believe the answer to this question is:

 char const * foo( ){ 

which says you are returning a pointer to a constant character.

+1
Apr 10 '14 at
source share



All Articles