Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Variable in Programming
Next article icon

Variable in Programming

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Variables in Programming

Table of Content

  • What are Variables In Programming?
  • Declaration of Variables In Programming
  • Initialization of Variables In Programming
  • Types of Variables In Programming
  • Difference between Variable and Constant
  • Difference between Local variables and Global Variables
  • Naming Conventions
  • Scope of a variable

What is a Variable in Programming?

Variable 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 Variable 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() {     // Syntax: datatype variable_name;     int age;     double price;     char grade;      return 0; } 
Java
/*package whatever //do not write package name here */  import java.io.*;  class GFG {     public static void main(String[] args)     {         // Syntax: datatype variable_name;         int age;         double price;         char grade;     } } 
Python
# No explicit declaration is required in Python; variables are dynamically typed. age = 25 price = 10.99 grade = 'A' 
C#
using System;  class Program {     static void Main()     {         // Suppress warnings for unused variables #pragma warning disable CS0168         int age;         double price;         char grade; #pragma warning restore CS0168          // These variables are declared but not used in this code block     } } 
JavaScript
// Syntax: var/let/const variable_name; var age; let price; const grade = 'A';  // Note: Constants need to be initialized during declaration. 

Output

Initialization of Variable 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() {      // Declaration and Initialization     int age = 25;     double price = 10.99;     char grade = 'A';      return 0; } 
Java
/*package whatever //do not write package name here */  import java.io.*;  class GFG {     public static void main(String[] args)     {         // Declaration and Initialization         int age = 25;         double price = 10.99;         char grade = 'A';     } } 
Python
# Initialization (no explicit declaration required) age = 25 price = 10.99 grade = 'A' 
C#
using System;  class Program {     static void Main()     {         // Declaration and Initialization         int age = 25;         double price = 10.99;         char grade = 'A';          // Displaying the values (optional)         Console.WriteLine($"Age: {age}");         Console.WriteLine($"Price: {price}");         Console.WriteLine($"Grade: {grade}");          // The equivalent of 'return 0;' is just ending the Main method     } } 
JavaScript
// Initialization using var (older syntax) var age = 25; // Initialization using let (block-scoped) let price = 10.99; // Initialization using const (block-scoped constant) const grade = 'A'; 

Output

Types of Variable 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
/*package whatever //do not write package name here */  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();     } } 
Python
global_variable = 5   def gfg_fnc():     print(global_variable)   def main():     print(global_variable)     gfg_fnc()   if __name__ == &quot;__main__&quot;:     main() 
C#
using System;  class Program {     // Declaring a static global variable accessible to all methods in the class     static int globalVariable = 5;      // Defining a method to print the value of the global variable     static void gfgFnc()     {         // Output the value of the global variable         Console.WriteLine(globalVariable);     }      static void Main(string[] args)     {         // Output the value of the global variable in the Main method         Console.WriteLine(globalVariable);          // Call the gfgFnc method to print the global variable's value         gfgFnc();     } } 
JavaScript
// Define a class named GFG class GFG {     // Define a static variable     static globalVariable = 5;      // Define a static method     static gfgFnc() {         console.log(GFG.globalVariable);     }      // Define the main method     static main() {         console.log(GFG.globalVariable);          // Call the static method gfgFnc         GFG.gfgFnc();     } }  // Call the main method of the GFG class GFG.main(); 

Output
5 5 

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
/*package whatever //do not write package name here */  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);         }     } } 
Python
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__ == &quot;__main__&quot;:     main() 
C#
using System;  class Program {     // Define a function named gfgFnc     static void gfgFnc()     {         // Declare and initialize a local variable named localVariable2         int localVariable2 = 10;         // Print the value of localVariable2         Console.WriteLine(localVariable2);     }      static void Main(string[] args)     {         // Declare and initialize a local variable named localVariable1         int localVariable1 = 5;         // Print the value of localVariable1         Console.WriteLine(localVariable1);          // Call the function gfgFnc         gfgFnc();          // Using if block to create a local scope         if (true)         {             // Declare and initialize a local variable named localVariable3             int localVariable3 = 15;             // Print the value of localVariable3             Console.WriteLine(localVariable3);         }          // Return 0 to indicate successful completion     } } 
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);     } }  // Call the main function main(); 

Output
5 10 15 

Difference between Variable and Constant:

CharacteristicVariableConstant
DefinitionA 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.
MutabilityCan be changed or reassigned during the execution of the program.Cannot be changed once assigned a value.
Declaration and InitializationMust 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.
Examplesint count = 5;const double PI = 3.14159;
Use CasesUsed for storing values that may vary or change during program execution.Used for storing fixed values or parameters that should not be modified.
Memory AllocationAllocates memory space to store the value.Allocates memory space to store the value, similar to variables.
SyntaxdataType variableName = value;const dataType constantName = value;

Difference between Local variables and Global Variables:

CharacteristicGlobal VariablesLocal Variables
Scope1Accessible throughout the entire codebaseConfined to the block, function, or scope of declaration.
VisibilityAccessible by any part of the program, including functions, blocks, or modulesAccessible only within the limited context of declaration.
LifetimeExist for the entire duration of the programIt exists only during the execution of the block or function.
InitializationMay have a default value, can be initialized outside functions or blocksMay not have a default value, and must be explicitly initialized within the scope.
Access from FunctionsAccessible directly from any function or blockDirectly 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() {     // Variable with local scope     int localVar = 10;     cout << "Inside myFunction: " << localVar << endl; }  int main() {      myFunction();  // Calling the function      return 0; } 
Java
public class Main {      public static void myFunction() {         // Variable with local scope         int localVar = 10;          // Accessing the local variable         System.out.println("Inside myFunction: " + localVar);     }      public static void main(String[] args) {          myFunction();  // Calling the function     } } 
Python
def my_function():     # Variable with local scope     local_var = 10     # Accessing the local variable     print("Inside my_function:", local_var)  my_function()  # Calling the function 
C#
using System;  class Program {     static void MyFunction()     {         // Variable with local scope         int localVar = 10;          // Accessing the local variable         Console.WriteLine("Inside MyFunction: " + localVar);     }      static void Main()     {         // Attempting to access the local variable from Main (not allowed)         // Uncommenting the line below will result in a compilation error         // Console.WriteLine("Inside Main: " + localVar);          MyFunction();  // Calling the function     } } 
JavaScript
function myFunction() {     // Variable with local scope     let localVar = 10;     console.log("Inside myFunction:", localVar); }  // Calling the function 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;  // Variable with global scope int globalVar = 20;  void myFunction() {     // Accessing the global variable     cout << "Inside myFunction: " << globalVar << endl; }  int main() {     // Accessing the global variable from main     cout << "Inside main: " << globalVar << endl;      myFunction();  // Calling the function      return 0; } 
Java
public class Main {     // Variable with class (global) scope     static int globalVar = 20;      public static void myFunction() {         // Accessing the global variable         System.out.println("Inside myFunction: " + globalVar);     }      public static void main(String[] args) {         // Accessing the global variable from the main method         System.out.println("Inside main: " + globalVar);          myFunction();  // Calling the function     } } 
Python
# Variable with global scope global_var = 20  def my_function():     # Accessing the global variable     print("Inside my_function:", global_var)  # Accessing the global variable from the global scope print("Inside global scope:", global_var)  my_function()  # Calling the function 
C#
using System;  class Program {     // Variable with global scope     static int globalVar = 20;      static void MyFunction()     {         // Accessing the global variable         Console.WriteLine("Inside MyFunction: " + globalVar);     }      static void Main()     {         // Accessing the global variable from Main         Console.WriteLine("Inside Main: " + globalVar);          MyFunction();  // Calling the function     } } 
JavaScript
// Variable with global scope let globalVar = 20;  function myFunction() {     // Accessing the global variable     console.log("Inside myFunction: " + globalVar); }  function main() {     // Accessing the global variable from main     console.log("Inside main: " + globalVar);      myFunction(); // Calling the function }  main(); // Call the main function 

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.


Next Article
Variable in Programming

A

alphacozeop
Improve
Article Tags :
  • Programming

Similar Reads

  • Learn Programming For Free
    Programming, also known as coding, is the process of creating a set of instructions that tell a computer how to perform a specific task. These instructions, called programs, are written in a language that the computer can understand and execute. Welcome to our journey into the world of programming!
    6 min read
  • What is Programming? A Handbook for Beginners
    Diving into the world of coding might seem intimidating initially, but it is a very rewarding journey that allows an individual to solve problems creatively and potentially develop software. Whether you are interested out of sheer curiosity, for a future career, or a school project, we are here to a
    13 min read
  • How to Start Coding: A Beginner's Guide to Learning Programming
    In today's digital age, learning programming has become increasingly important. As technology continues to advance, the demand for skilled programmers across various industries is on the rise. Whether you want to pursue a career in tech, develop problem-solving skills, or simply unleash your creativ
    15+ min read
  • Basic Components of Programming

    • Data Types in Programming
      In Programming, data type is an attribute associated with a piece of data that tells a computer system how to interpret its value. Understanding data types ensures that data is collected in the preferred format and that the value of each property is as expected. Table of Content What are Data Types
      11 min read
    • Variable in Programming
      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. Table
      11 min read
    • Variable in Programming
      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. Table
      11 min read
    • Types of Operators in Programming
      Types of operators in programming are symbols or keywords that represent computations or actions performed on operands. Operands can be variables, constants, or values, and the combination of operators and operands form expressions. Operators play a crucial role in performing various tasks, such as
      15+ min read
    • Conditional Statements in Programming | Definition, Types, Best Practices
      Conditional statements in programming are used to control the flow of a program based on certain conditions. These statements allow the execution of different code blocks depending on whether a specified condition evaluates to true or false, providing a fundamental mechanism for decision-making in a
      15+ min read
    • If-Then-___ Trio in Programming
      Learning to code is a bit like discovering magic spells, and one trio of spells you'll encounter often is called "If-Then-___." These spells help your code make decisions like a wizard choosing the right spell for a particular situation. Table of Content If-Then-ElseIf-Then-TernaryIf-Then-ThrowIf-Th
      2 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences