Is the pointer returned by the following function valid?
const char * bool2str( bool flg )
{
return flg ? "Yes" : "No";
}
It works well in Visual C++ and g++. What does C++ standard say about this?
Is the pointer returned by the following function valid?
const char * bool2str( bool flg )
{
return flg ? "Yes" : "No";
}
It works well in Visual C++ and g++. What does C++ standard say about this?
Technically Yes it is valid.
The strings have static storage durataion.
But that is not the whole story.
These are C-Strings. The convention in C-Libraries and funcctions is to return a dynamically allocated string that should be freed. ie A pointer returned is implicitly passing ownership back to tha caller (As usuall in C there are also exceptions).
If you do not follow these conventions you will confuse a lot of experienced C-Developers that would expect this convention. If you do not follow this standard expectation then it should be well documented in the code.
Also this is C++ (as per your tags). So it is more conventional to return a std::string. The reason for this is that the passing of ownership via pointers is only implied (and this lead to a lot of errors in C code were the above expectation was broken but documented, unfortunately the documentaiton was never read by the user of the code). By using a std::string you are passing an object and their is no longer any question of ownership (the result is passed back as a value and thus yours), but because it is an object there is no questions or issues with resource allocation.
If you are worried about effeciency I think that is a false concern.
If you want this for printing via streams there is already a standard convention to do that:
This code is perfectly valid and conformant. The only "gotcha" would be to ensure that the caller doesn't try to free the string.
On storage duration:
read in conjunction with 3.7.1
On type:
Dynamically allocated (the word 'heap' is never used in context of an area of memory AFAIK in the standard) memory requires a function call that can happen as early as
main
much after the static memory is allocated.This code is valid and standard compliant.
String literals are stored in read-only memory, and the function just gets the address of the chosen string.
C++ standard (2.13.4) says :
They key to understand your problem here, is the static storage duration : string literals are allocated when your program launch, and last for the duration of the program. Your function just gets the address and returns it.