Example of Local Variable
Here are the example of local variable in different language:
#include <iostream>
using namespace std;
void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y;
cout << "The sum is: " << z << endl;
}
int main() {
exampleFunction();
return 0;
}
public class Main {
public static void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y;
System.out.println("The sum is: " + z);
}
public static void main(String[] args) {
exampleFunction();
}
}
using System;
public class Program {
public static void ExampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y;
Console.WriteLine("The sum is: " + z);
}
public static void Main(string[] args) {
ExampleFunction();
}
}
function exampleFunction() {
// Local variable declaration
var x = 10;
var y = 20;
var z = x + y;
console.log("The sum is: " + z);
}
exampleFunction();
def example_function():
# Local variable declaration
x = 10
y = 20
z = x + y
print("The sum is:", z)
example_function()
Output
The sum is: 30
Local and Global Variables
Local variables are declared within a specific block of code, such as a function or method, and have limited scope and lifetime, existing only within that block. Global variables, on the other hand, are declared outside of any function and can be accessed from any part of the program, persisting throughout its execution.
Table of Content
- Local Variable
- Example of Local Variable
- Advantages of local variable
- Disadvantages of local variable
- Global Variable
- Example of Global Variable
- Advantages of global variable
- Disadvantages of global variable