Variables in Programming
Last Updated :
29 Feb, 2024
In programming, we often need a named storage location to store the data or values. Using variables, we can store the data in our program and access it afterward. In this article, we will learn about variables in programming, their types, declarations, initialization, naming conventions, etc.
Variables in Programming
What are Variables In Programming?
A Variables In Programming is a named storage location that holds a value or data. These values can change during the execution of a program, hence the term “variable.” Variables are essential for storing and manipulating data in computer programs. A variable is the basic building block of a program that can be used in expressions as a substitute in place of the value it stores.
Declaration of Variables In Programming:
In programming, the declaration of variables involves specifying the type and name of a variable before it is used in the program. The syntax can vary slightly between programming languages, but the fundamental concept remains consistent.
C++
#include <iostream>
using namespace std;
int main()
{
int age;
double price;
char grade;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int age;
double price;
char grade;
}
}
|
Python3
age = 25
price = 10.99
grade = 'A'
|
C#
using System;
class Program
{
static void Main()
{
#pragma warning disable CS0168
int age;
double price;
char grade;
#pragma warning restore CS0168
}
}
|
Javascript
var age;
let price;
const grade = 'A' ;
|
Initialization of Variables In Programming:
Initialization of variables In Programming involves assigning an initial value to a declared variable. The syntax for variable initialization varies across programming languages.
C++
#include <iostream>
using namespace std;
int main()
{
int age = 25;
double price = 10.99;
char grade = 'A' ;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int age = 25 ;
double price = 10.99 ;
char grade = 'A' ;
}
}
|
Python
age = 25
price = 10.99
grade = 'A'
|
C#
using System;
class Program
{
static void Main()
{
int age = 25;
double price = 10.99;
char grade = 'A' ;
Console.WriteLine($ "Age: {age}" );
Console.WriteLine($ "Price: {price}" );
Console.WriteLine($ "Grade: {grade}" );
}
}
|
Javascript
var age = 25;
let price = 10.99;
const grade = 'A' ;
|
Types of Variables In Programming:
1. Global Variables:
Global variables in programming are declared outside any function or block in a program and accessible throughout the entire codebase. In simpler words, Global variables can be accessed in any part of the program, including functions, blocks, or modules.
C++
#include <iostream>
using namespace std;
int globalVariable = 5;
void gfgFnc() { cout << globalVariable << endl; }
int main()
{
cout << globalVariable << endl;
gfgFnc();
return 0;
}
|
Java
import java.io.*;
class GFG {
static int globalVariable = 5 ;
static void gfgFnc()
{
System.out.println(globalVariable);
}
public static void main(String[] args)
{
System.out.println(globalVariable);
gfgFnc();
}
}
|
Python3
global_variable = 5
def gfg_fnc():
print (global_variable)
def main():
print (global_variable)
gfg_fnc()
if __name__ = = "__main__":
main()
|
C#
using System;
class Program
{
static int globalVariable = 5;
static void gfgFnc()
{
Console.WriteLine(globalVariable);
}
static void Main( string [] args)
{
Console.WriteLine(globalVariable);
gfgFnc();
}
}
|
Javascript
class GFG {
static globalVariable = 5;
static gfgFnc() {
console.log(GFG.globalVariable);
}
static main() {
console.log(GFG.globalVariable);
GFG.gfgFnc();
}
}
GFG.main();
|
2. Local Variables:
Local variables in programming are declared within a specific function, block, or scope and are only accessible within that limited context. In simpler words, Local variables are confined to the block or function where they are declared and cannot be directly accessed outside that scope.
C++
#include <iostream>
using namespace std;
void gfgFnc()
{
int localVariable2 = 10;
cout << localVariable2 << endl;
}
int main()
{
int localVariable1 = 5;
cout << localVariable1 << endl;
gfgFnc();
if ( true ) {
int localVariable3 = 15;
cout << localVariable3 << endl;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
static void gfgFnc()
{
int localVariable2 = 10 ;
System.out.println(localVariable2);
}
public static void main(String[] args)
{
int localVariable1 = 5 ;
System.out.println(localVariable1);
gfgFnc();
if ( true ) {
int localVariable3 = 15 ;
System.out.println(localVariable3);
}
}
}
|
Python3
def gfg_fnc():
local_variable_2 = 10
print (local_variable_2)
def main():
local_variable_1 = 5
print (local_variable_1)
gfg_fnc()
if True :
local_variable_3 = 15
print (local_variable_3)
if __name__ = = "__main__":
main()
|
C#
using System;
class Program
{
static void gfgFnc()
{
int localVariable2 = 10;
Console.WriteLine(localVariable2);
}
static void Main( string [] args)
{
int localVariable1 = 5;
Console.WriteLine(localVariable1);
gfgFnc();
if ( true )
{
int localVariable3 = 15;
Console.WriteLine(localVariable3);
}
}
}
|
Javascript
function gfgFnc() {
var localVariable2 = 10;
console.log(localVariable2);
}
function main() {
var localVariable1 = 5;
console.log(localVariable1);
gfgFnc();
if ( true ) {
var localVariable3 = 15;
console.log(localVariable3);
}
}
main();
|
Difference between Variable and Constant:
Characteristic |
Variable |
Constant |
Definition |
A variable is a symbol that represents a value that can change during program execution. |
A constant is a symbol that represents a fixed, unchanging value. |
Mutability |
Can be changed or reassigned during the execution of the program. |
Cannot be changed once assigned a value. |
Declaration and Initialization |
Must be declared before use, and its value can be initialized at declaration or later in the code. |
Must be assigned a value at the time of declaration, and its value cannot be changed afterward. |
Examples |
int count = 5; |
const double PI = 3.14159; |
Use Cases |
Used for storing values that may vary or change during program execution. |
Used for storing fixed values or parameters that should not be modified. |
Memory Allocation |
Allocates memory space to store the value. |
Allocates memory space to store the value, similar to variables. |
Syntax |
dataType variableName = value; |
const dataType constantName = value; |
Difference between Local variables and Global Variables:
Characteristic |
Global Variables |
Local Variables |
Scope1 |
Accessible throughout the entire codebase |
Confined to the block, function, or scope of declaration. |
Visibility |
Accessible by any part of the program, including functions, blocks, or modules |
Accessible only within the limited context of declaration. |
Lifetime |
Exist for the entire duration of the program |
It exists only during the execution of the block or function. |
Initialization |
May have a default value, can be initialized outside functions or blocks |
May not have a default value, and must be explicitly initialized within the scope. |
Access from Functions |
Accessible directly from any function or block |
Directly accessible only within the declaring function |
Naming Conventions:
Naming conventions for variables In Programming help maintain code readability and consistency across programming projects. While specific conventions can vary between programming languages, some common practices are widely followed. Here are general guidelines for naming variables:
- Descriptive and Meaningful: Choose names that indicate the purpose or content of the variable. A descriptive name improves code readability and understanding.
- Camel Case or Underscore Separation: Use camel case (myVariableName) or underscores (my_variable_name) to separate words in a variable name. Choose one style and stick to it consistently.
- Avoid Single Letter Names: Except for loop counters or well-known conventions (e.g., i for an index), avoid single-letter variable names. Use names that convey the variable’s purpose.
- Follow Language Conventions: Adhere to the naming conventions recommended by the programming language you are using. For example, Java typically uses camel case (myVariableName), while Python often uses underscores (my_variable_name).
- Avoid Reserved Words: Avoid using reserved words or keywords of the programming language as variable names.
- Avoid Abbreviations: Use full words instead of abbreviations, except when widely accepted or for standard terms (e.g., max, min).
Scope of a variable:
The scope of a variable in programming refers to the region of the program where the variable can be accessed or modified. It defines the visibility and lifetime of a variable within a program. There are typically two types of variable scope:
Local Scope:
- A variable declared inside a function, block, or loop has a local scope.
- It can only be accessed within the specific function, block, or loop where it is declared.
- Its lifetime is limited to the duration of the function, block, or loop.
C++
#include <iostream>
using namespace std;
void myFunction() {
int localVar = 10;
cout << "Inside myFunction: " << localVar << endl;
}
int main() {
myFunction();
return 0;
}
|
Java
public class Main {
public static void myFunction() {
int localVar = 10 ;
System.out.println( "Inside myFunction: " + localVar);
}
public static void main(String[] args) {
myFunction();
}
}
|
Python3
def my_function():
local_var = 10
print ( "Inside my_function:" , local_var)
my_function()
|
C#
using System;
class Program
{
static void MyFunction()
{
int localVar = 10;
Console.WriteLine( "Inside MyFunction: " + localVar);
}
static void Main()
{
MyFunction();
}
}
|
Javascript
function myFunction() {
let localVar = 10;
console.log( "Inside myFunction:" , localVar);
}
myFunction();
|
Output
Inside myFunction: 10
Global Scope:
- A variable declared outside of any function or block has a global scope.
- It can be accessed from anywhere in the program, including inside functions.
- Its lifetime extends throughout the entire program.
C++
#include <iostream>
using namespace std;
int globalVar = 20;
void myFunction() {
cout << "Inside myFunction: " << globalVar << endl;
}
int main() {
cout << "Inside main: " << globalVar << endl;
myFunction();
return 0;
}
|
Java
public class Main {
static int globalVar = 20 ;
public static void myFunction() {
System.out.println( "Inside myFunction: " + globalVar);
}
public static void main(String[] args) {
System.out.println( "Inside main: " + globalVar);
myFunction();
}
}
|
Python
global_var = 20
def my_function():
print ( "Inside my_function:" , global_var)
print ( "Inside global scope:" , global_var)
my_function()
|
C#
using System;
class Program
{
static int globalVar = 20;
static void MyFunction()
{
Console.WriteLine( "Inside MyFunction: " + globalVar);
}
static void Main()
{
Console.WriteLine( "Inside Main: " + globalVar);
MyFunction();
}
}
|
Javascript
let globalVar = 20;
function myFunction() {
console.log( "Inside myFunction: " + globalVar);
}
function main() {
console.log( "Inside main: " + globalVar);
myFunction();
}
main();
|
Output
Inside main: 20
Inside myFunction: 20
Understanding and managing variable scope is crucial for writing maintainable and bug-free code, as it helps avoid naming conflicts and unintended side effects.
In conclusion, variables In programming are fundamental elements in programming, serving as named storage locations to hold and manipulate data. They are crucial in writing dynamic, adaptable, and functional code. The proper use of variables, adherence to clear naming conventions, and understanding of scope contribute to code readability, maintainability, and scalability.
Share your thoughts in the comments
Please Login to comment...