Variables in C++

Aarav Iyer
2 min readJun 15, 2023

--

The official C++ logo. Source: https://dwglogo.com/cplusplus/

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; }

Try It Out Here

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 don’t 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 <iostream> 
using namespace std;
int main()
{
cout << "Constants in C++.\n";
const int x=20;
cout << x;
}

Try It Out Here

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

Originally published at https://pycodingguide.blogspot.com

--

--

Aarav Iyer
Aarav Iyer

Written by Aarav Iyer

A tech enthusiast learning Python and interested in anything related to space and the Universe.

No responses yet