Example of Global Variable
Here are the example of global variable in different language:
#include <iostream>
using namespace std;
// Global variable declaration
int global_var = 100;
void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y + global_var;
cout << "The sum is: " << z << endl;
}
int main() {
exampleFunction();
return 0;
}
public class Main {
// Global variable declaration
static int global_var = 100;
public static void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y + global_var;
System.out.println("The sum is: " + z);
}
public static void main(String[] args) {
exampleFunction();
}
}
using System;
public class Program {
// Global variable declaration
static int global_var = 100;
public static void ExampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y + global_var;
Console.WriteLine("The sum is: " + z);
}
public static void Main(string[] args) {
ExampleFunction();
}
}
// Global variable declaration
var global_var = 100;
function exampleFunction() {
// Local variable declaration
var x = 10;
var y = 20;
var z = x + y + global_var;
console.log("The sum is: " + z);
}
exampleFunction();
# Global variable declaration
global_var = 100
def example_function():
# Local variable declaration
x = 10
y = 20
z = x + y + global_var
print("The sum is:", z)
example_function()
Output
The sum is: 130
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