Variables and Constants

Variables and Constants

Understanding Variables and Constants

Variables

  • Variables are named locations in computer memory used to store data.
  • This data or value can be changed, or varied, during program execution, hence the term ‘variable’.
  • Every variable has a datatype, which identifies the type of data it should store. Examples of datatypes include integers, boolean, float, string etc.
  • Variable names should be descriptive and follow a naming convention like CamelCase or underscores to increase program readability.
  • A variable must be declared before it can be used in a program.

Constants

  • Constants are similar to variables as they are also named locations to store data.
  • However, the value of a constant cannot be changed during program execution, making it constant.
  • Constants are also required to be declared before they can be used in a program.
  • Constants are usually used to define fixed values that should not be altered, such as PI, gravity, tax rates etc.
  • Like variables, constants also have datatypes.

Declaration and Assignment

  • Declaration is the process of defining a variable or constant in a program.
  • In many programming languages, you declare a variable by stating its datatype followed by its name.
  • Assignment refers to the action of initializing or updating the value of a variable.
  • You can declare and assign a variable or constant at the same time or in separate steps.
  • In most languages, you use the assignment operator ‘=’ to assign a value to a variable.

Scope of Variables and Constants

  • Scope describes the region of code where a variable or constant can be accessed.
  • Variables declared within a function or a loop, known as local variables, are only accessible within that function or loop.
  • Variables declared outside all functions, known as global variables, are accessible throughout the entire program.
  • Constants are generally global and can be accessed throughout the entire program.

Lifetime of Variables and Constants

  • The lifetime of a variable or constant begins when it is declared and ends when the program stops running or the function it was declared in is finished executing.
  • Local variables have shorter lifetimes as they cease to exist when the function they are declared in ends.
  • Global variables and constants usually have lifetimes that span the entire execution time of the program.

Key Takeaway

  • Understanding and using variables and constants correctly is fundamental to successful programming and avoids common errors.