A variable is a storage place that has some memory allocated to it. It is used to store some form of data. Different types of variables require different amounts of memory.
Variable Declaration-
In C++, we can declare variables as follows:
-
data_type: Type of the data that can be stored in this variable. It can be int, float, double, etc.
-
variable_name: Name given to the variable.
data_type variable_name;
Example: int x;
In this way, we can only create a variable in the memory location. Currently, it doesn’t have any value. We can assign the value in this variable by using two ways:
- By using variable initialization.
- By taking input
Here, we can discuss only the first way, i.e., variable initialization. We will discuss the second way later.
data_type variable_name=value;
Example: int x = 20;
Rules for defining variables in C++
- You can’t begin with a number. Ex- 9a can't be a variable, but a9 can be a variable.
- Spaces and special characters except for underscore(_) are not allowed.
- C++ keywords (reserved words) must not be used as a variable name.
- C++ is case-sensitive, meaning a variable with the name ‘A’ is different from a variable with the name ‘a’. (Difference in the upper-case and lower-case holds true).
C++ Keywords ![[Pasted image 20240718010527.png]]
All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types tell the variables the type of data they can store.
Pre-defined data types available in C++ are:
● int: Integer value
● unsigned int: Can store only positive integers.
● float, double: Decimal number
● char: Character values (including special characters)
● unsigned char: Character values
● bool: Boolean values (true or false)
● long: Contains integer values but with the larger size
● unsigned long: Contains large positive integers or 0
● short: Contains integer values but with a smaller size
Table for datatype and its size in C++: (This can vary from compiler to compiler and system to system depending on the version you are using)
Examples:
int price = 5000; // Integer (whole number)
float interestRate = 5.99f; // Floating point number
char myLetter = 'D'; // Character
bool isPossible = true; // Boolean
string myText = "Coding Ninjas"; // String
auto keyword in c++
The auto keyword specifies that the type of the declared variable will automatically be deduced from its initializer. It would set the variable type to initialize that variable’s value type or set the function return type as the value to be returned.
Example:
auto a = 11 // will set the variable a as int type
auto b = 7.65 //will set the variable b as float
auto c = "abcdefg" // will set the variable c as string