Functions can return references, but this can be dangerous. When returning a reference to a variable declared in the called function, unless that variable is declared static
, the reference refers to an automatic variable that’s discarded when the function terminates. An attempt to access such a variable yields undefined behavior. References to undefined variables are called dangling references.
Common Programming Error 6.9
Returning a reference to an automatic variable in a called function is a logic error. Compilers typically issue a warning when this occurs. For industrial-strength code, always eliminate all compilation warnings before producing executable code.
18.116.81.208