Supposedly, returning a literal by reference in C++ is bad since the literal goes out of scope then leaving the function:
const char &ToBoolean(bool val) const
{
return val ? (const char &)"1" : (const char &)"0";
}
, but when using inline
I'm guessing this should be ok since the literal's scope is now in the calling function, or no? Example:
inline const char &ToBoolean(bool val) const
{
return val ? (const char &)"1" : (const char &)"0";
}
This is how I plan to use it:
void testToBoolean1()
{
bool val = true;
const char *valStr = ToBoolean(val);
int result = strcmp("1", valStr);
CPPUNIT_ASSERT_EQUAL(0, result);
}
Update.
If static strings are ok, then how about this?
inline const char *ToBoolean(bool val) const {
char boolStr[6];
if (val) strcpy(boolStr, "true");
else strcpy(boolStr, "false");
return &boolStr;
}
This compiles and runs fine using VC++ 2012.