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
#include <iostream>using namespace std;int main(){int first_number, second_number, sum;cout << "Enter two integers: ";// Two integers entered by user storedcin >> first_number >> second_number;// Sum of the two numbers stored in the variable sumsum = first_number + second_number;// Displaying the value of sumcout << first_number << "+" << second_number << "=" << sum;return 0;}
Output:
Enter two integers: 7 17 7 + 17 = 24