I was thinking about this. Let's say I wish to return an empty cstring if "test" is false. From the above 2 functions, is function 2 the correct way of returning a char*? I am guessing function 1 will return an incorrect pointer because no static variable is assigned to it, and thus it is pointing to an incorrect memory location?
I have tried to test it with something like this:
if (myFunction1(false)[0] == '\0' )
{
Serial.println("ok");
}
if (myFunction2(false)[0] == '\0' )
{
Serial.println("ok");
}
But both printed "ok". So I am obviously not sure if function 1 is also correct now. Could someone advise.
Thanks for the replies. "return a pointer that points to nowhere" is one of the things what I needed to know. I have thought of returning NULL, but the thing is I sometimes would like to use the returned value directly in a strcmp function.
So I noticed that if the result returned is NULL, and I don't do additional checking for it first, it will crash. But if I return an empty string instead, the strcmp function won't crash.
Edit: I just tested, returning NULL/nullptr in strcmp function on Arduino does not crash, but crashes on ESP8266. Well well now I know.
Byork:
But I noticed BulldogLowell used nullptr instead of NULL, I'm not sure of the difference at this moment or if it will make a difference. I will test it soon when I get a chance.
I think that using the nullptr keyword improves the readability of the code.
I would expect both to functions work. Are not string constants assigned static addresses?
One change you should do, at least for myFunction1(): Make the return type 'const chr *'. Without the 'const' keyword and with warnings turned up you get a warning when you try to return "" as a 'char *'.