C++ Variables

Variables in C++ are used store a value. C++ allows the declaration of a variable anywhere in the scope. It means that a variable can be declared right at the place of its first use. There are some rules in C++ for choosing a variable name as same a C. They are following:

  • Must begin with a letter or underscore.
  • First 31 characters are significant.
  • Variables name are case sensitive.
  • consist of Capital letters(A-Z), lowercase letters(a-z), digits(0-9), and the underscore character.
  • Should not be a keyword.
  • White space is not allowed.
  • Special characters are not allowed.

There are the following variable types in C++:

Type Description
char Used to store characters and letters
int Used to store an integer.
float Used to store single-precision floating point value.
double Used to store double-precision floating point value.
void Comprises an empty set of values.
wchar_t Represents a wide character type.

Example of a c++ program using variable is given below:

Example

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int first_number, second_number, sum;
  6. cout << "Enter two integers: ";
  7. // Two integers entered by user stored
  8. cin >> first_number >> second_number;
  9. // Sum of the two numbers stored in the variable sum
  10. sum = first_number + second_number;
  11. // Displaying the value of sum
  12. cout << first_number << "+" << second_number << "=" << sum;
  13. return 0;
  14. }

Output:

Enter two integers: 7
17
7 + 17 = 24