Home > Backend Development > C++ > body text

What is the lifetime of local variables of a C++ function?

王林
Release: 2024-04-20 08:57:01
Original
798 people have browsed it

C Local variables of a function exist during function execution and are destroyed when the function returns. Their scope is limited to the function and cannot be accessed outside the function.

C++ 函数的局部变量的生存期有多长?

The lifetime of local variables of C function

In C, local variables are variables declared and initialized inside the function . Their scope is limited to that function, meaning they can only be accessed and modified during function execution.

The lifetime of local variables:

  • Local variables are created when the function is called.
  • Local variables exist during function execution.
  • Local variables are destroyed when the function returns.

Practical case:

Let us consider the following C function:

void printNumbers() {
  int number = 10;  // 局部变量
  cout << "Number: " << number << endl;
}
Copy after login

When the printNumbers() function is When called, the local variable number will be created and initialized to 10. This variable will exist during the execution of the function, that is, after the statement where it prints "Number: 10". When the function returns, number is destroyed so it cannot be accessed outside the function.

Points:

  • The scope of a local variable is limited to the function in which it is declared.
  • Local variables exist during function execution and are destroyed when the function returns.
  • Local variables cannot be accessed outside the function.

The above is the detailed content of What is the lifetime of local variables of a C++ function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template