If above is legal
It is syntactically correct.
Is it semantically correct? It depends on what you do with the pointer.
The line
return &str[0];
returns a pointer to an object that won't be alive after the function returns. The pointer is a dangling pointer in the calling function.
If you try to dereference the poiner, your code is subject to undefined behavior.
if ( *(foo()) == 'a' ) { ... } // Not OK.
If you use the pointer simply as a pointer without dereferencing it, the code should be OK. For example, you can compare the returned value against nullptr
.
if ( foo() == nullptr ) { ... } // OK.
Anecdotal Note
I have seen commercially deployed code that uses addresses of function local variables to deduce whether the stack grows up or down in a platform.
char* foo()
{
char c;
return &c;
}
bool stackGrowsUp()
{
char c;
return (&c < foo());
}