Fihop
Fihop

Reputation: 3177

return const value for built-in type

Is it a good custom to return a const value for built-in type?

The reason is:

const int F()
{
}

int y;
F(x) = y;

The above code will not compile if the return value is const. However if it's not, F(x) = y; is a very hidden mistake.

Since it has no meaning to assign a value to a function, I'm thinking is it a good custom to always return a const value for built-in type? If I always return a const value for built-in type, is there any problem?

Upvotes: 3

Views: 876

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507433

const means that during the lifetime of an object, the value of the object does not change.

The Standard itself notes that hence, const does not make sense on prvalues of nonclass or nonarray prvalues. Such expressions never refer to objects (at least if the expression originates from user code. The language itself may create prvalues during reference binding which magically refer to temporary objects. IMHO, though, these should be xvalues instead). Hence since there is no object, there is no lifetime. And hence, there is nothing to be held "const".

Upvotes: 5

Jamey Sharp
Jamey Sharp

Reputation: 8511

Assigning to a function call of this type isn't legal anyway. g++ gives me this error message if I try:

test.cpp: In function ‘int main()’:
test.cpp:8:8: error: lvalue required as left operand of assignment

So you don't need to also declare the return value const just to get a suitable diagnostic from the compiler.

Upvotes: 3

Related Questions