Home > Backend Development > C++ > Why is Returning a Reference to a Local C Variable Generally Discouraged?

Why is Returning a Reference to a Local C Variable Generally Discouraged?

Patricia Arquette
Release: 2024-12-08 18:12:12
Original
887 people have browsed it

Why is Returning a Reference to a Local C   Variable Generally Discouraged?

Returning a Reference to a Local Variable

In C , returning a reference to a local variable is generally discouraged as it can lead to dangling references. However, in certain circumstances, it may still appear to work, as in the example below:

int& foo()
{
    int i = 6;
    std::cout << &i << std::endl;
    return i;
}

int main()
{
    int i = foo();
    std::cout << i << std::endl;
    std::cout << &i << std::endl;
}
Copy after login

This code compiles and runs without errors, and it prints:

0xfefef2
6
0x7ffe82600698
Copy after login

Contrary to expectations, the variable i in main() still holds the value 6 after the call to foo() has returned. This is because, in this case, the compiler has extended the lifetime of the local variable past the end of the foo() function.

This behavior is implementation-specific and should not be relied upon. In general, it is considered good practice to avoid returning references to local variables. If you need to return the value of a local variable, it is preferable to return it by value instead.

The above is the detailed content of Why is Returning a Reference to a Local C Variable Generally Discouraged?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template