Variables in C++ are to be written in a bracket next to the data type intended for the variable. The main data types are given here. For example;
#include <iostream> using namespace std; int main() { cout<<"C++ Variables.\n"; char x; cout<<"Enter any character:"; cin>>x; cout<<"Your character is:"<<x; }
This adding of the data type before the variable is called declaring the variable. Every variable has to be declared before it can be executed.
Rules for declaring variables in C++
- The variable can contain letters, digits and underscores.
- The variable needs to begin with a letter of the alphabet or an underscore.
- The name of the variable can not contain whitespace or special characters.
- Any C++ keyword (for eg. float, int, char, etc.) cannot be used as a variable.
- The name of the variable is case sensitive. For example, 'coding' is different from 'Coding'.
You can declare multiple variables by adding a comma between the variables after the data type.
The concept of variables is quite simple in C++ and does not require much thought. If you remember how to declare a variable and remember the rules, you are good.
Constants
When you dont want anyone changing the value of a variable, you can change it into a constant. Constant has a keyword 'const' which needs to be added before the data type of the variable. For example;
#includeusing namespace std; int main() { cout << "Constants in C++.\n"; const int x=20; cout << x; }
That is all for this post. Follow this blog to get more info on coding and coding languages.
Regards,
Aarav Iyer
References:
(1) https://www.geeksforgeeks.org/cpp-variables/
(2) https://www.w3schools.com/cpp/cpp_variables.asp