Variables in C++

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++

  1. The variable can contain letters, digits and underscores.
  2. The variable needs to begin with a letter of the alphabet or an underscore.
  3. The name of the variable can not contain whitespace or special characters.
  4. Any C++ keyword (for eg. float, int, char, etc.) cannot be used as a variable.
  5. 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;

#include 
using 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

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

Post a Comment

Next Post Previous Post