Variables and constants

Home / C ++ Programming / Variables and constants

Variables and constants


What are Variables?

Variables are fundamental components in programming languages like C++. They act as containers to store data values that can change during the execution of a program. Think of them as named placeholders for storing information in the computer's memory.


Declaration and Initialization:
  • Declaration: To create a variable, you declare its type and name. This informs the compiler about the type of data the variable will hold and reserves memory space accordingly.
  int age;         // Declaration of an integer variable named 'age'

Initialization: After declaring a variable, you can initialize it by assigning a value. Initialization sets the initial value of the variable.




age = 25;      // Assigning the value 25 to the variable 'age'

Variable Naming Rules:

  • Variable names must begin with a letter (uppercase or lowercase) or an underscore (_).
  • Subsequent characters can be letters, digits, or underscores.
  • Variable names are case-sensitive (age, Age, and AGE are different).
  • Avoid using reserved keywords (words with special meaning in C++) as variable names.

Variable Types:

  • Data Types: Variables have types that determine what kind of data they can store. For example, int, float, char, bool, etc.
  • Size and Memory: Each variable type occupies a specific amount of memory in the computer's memory, and its size depends on the data type.

Using Variables:

  • Assignment: You can change the value stored in a variable by assigning a new value to it.



age = 30; // Changing the value of 'age' from 25 to 30



Usage: Variables can be used in expressions and statements throughout the program.




int total_age = age + 10; // Using 'age' in an expression to calculate 'total_age'



Scope of Variables:

  • Scope: Variables have a scope, which defines where in the program they are accessible. Variables declared within a block of code are typically only accessible within that block (local scope), while variables declared outside of any function or block are accessible throughout the program (global scope).