Here is an example of returning const char*
with nullptr
as a special type of "sentinel value" to mean "false":
There are a lot of potential things to address here, and we don't really understand your purpose of the function or use-case, but let me just address your immediate code and one viable solution.
There are many potential ways to handle this. Again, here is just one. But, I have to make some assumptions to even answer. Let's assume that:
- Your function needs to return either a string literal OR
false
(or something equivalent to represent this).
- This means you will NOT be generating a string at run-time inside the function. You will ONLY return a string literal (meaning: a compile-time-constant string with double quotes around it like this:
"some string literal"
) which is set in your source code and fixed at compile-time. Otherwise, my example may not meet your needs, and would need some changes.
- You will never need to return
true
. Rather, the existence of a string indicates true
as well.
In this case:
// 1. Change this:
int comparehex(byte hex[])
// to this:
const char* comparehex(byte hex[])
// 2. change this:
return false;
// to this:
return nullptr;
// now this line is fine too:
return "string";
Now, the function returns either nullptr
to indicate false
, OR a string literal such as "string"
.
You'd simply check to see if "false" was intended by checking like this:
const char* str = comparehex(some_hex_array);
if (str == nullptr)
{
// `comparehex()` essentially returned `false`, so do what you need to do here
}
else
{
// str was set to some string, so use its value (ex: print it)
printf("%s\n", str);
}
Final notes:
- Again, if you're generating a new string inside the function at run-time, rather than returning a string literal set at compile-time, the above 2 changes are not sufficient.
- Also note that the above code is rather "C-like". It is perfectly valid C++, but only one of many ways to handle the above scenario.
- And lastly,
nullptr
here can be considered a type of "sentinel value", which means simply that it is a special value of your return type (const char*
) to indicate a special meaning: false
in this case. And therefore, by extension, this sentinel value of nullptr
also possesses the special meaning of whatever you intend "false" to mean.
Related
- For another generic example of returning
const char*
, see my const char * reset_cause_get_name(reset_cause_t reset_cause)
function in my answer in C here: STM32 how to get last reset status. I don't return NULL
(the C analogue to C++'s nullptr
) for cases where no match is found, but I could. (In my example I set it to "TBD"
instead of NULL
).
- See also: What exactly is nullptr?