Variables in c++

  • C++ allows you to store values in variables. Each variable is identified by a variable name.
  • Additionally, each variable has a variable type. The type tells C++ how the variable is going to be used and what kind of numbers (real, integer) it can hold.
  • A variable must be defined before you can use it in a program.
  • When you define a variable the type is specified and an appropriate amount of memory reserved.
  • This memory space is addressed by reference to the name of the variable.
  • Some programming languages do not require programmers to declare variables before they are used; the type of a variable is determined by how the variable is used.
  • Some languages allow the same variable to assume different types as its use differs in different parts of a program.

Variable Declarations

Before you can use a variable in C++, it must be defined in a declaration statement. A variable cannot be used unless it is declared.

A variable declaration serves three purposes:

  • It defines the name of the variable.
  • It defines the type of the variable (integer, real, character, etc.).
  • It gives the programmer a description of the variable.
  • type name; // comment
  • Type is one of the C++ variable types (int, float, etc.) Name is any valid variable name. The comment explains what the variable is and what it will be used for.
  • Variable declarations come just before the main() line at the top of a program.