Local Variables

Anonymous contributor's avatar
Anonymous contributor
Published Nov 12, 2024
Contribute to Docs

A local variable is a variable whose scope is limited to the function or block where it is defined. It exists only within that function and can only be accessed from there.

Syntax

void local_variable(){
    int a_local_variable;
}

The variable a_local_variable is local to the local_variable function in which it is defined. It can only be accessed and used within that function. When the function local_variable exits, the life of a_local_variable ends, and its memory is released.

Example

In the following example, the a_local_variable of integer data type is defined inside the function local_variable():

#include <iostream>
using namespace std;
void local_variable(){
int a_local_variable = 1;
cout <<a_local_variable;
}
int main()
{
local_variable();
}

The output of the above code will be:

1

Codebyte Example

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy