C++ Variables & Types
In this tutorial, you’ll learn about variables and data types in C++ programming language and how to use them.
Variables in C++
A variable is a container for storing data in your C++ program.
Each variable should be given a distinct name to denote the storage area (identifier). A variable’s name can be made up of letters, digits, and the underscore character. It has to start with a letter or an underscore. Because C++ is case-sensitive, uppercase and lowercase letters are separate. You cannot use the built-in C++ keyword as variable name.
Declaring a Variable in C++
C++ is a strongly typed language, which means that each variable must be declared with its type before being used for the first time. This tells the compiler how to interpret the variable’s value and how much memory to set aside for it.
We use a particular type of declaration statement called a definition to create a variable. Here’s how we define a variable in C++.
int id;
When the compiler encounters this statement, it notes that we’re defining a variable and giving it the name id, as well as the fact that it’s of type int.
C++ supports a variety of types out of the box, including integers. We’ll look in to them in the next chapter about the data types.
Initializing a Variable in C++
When variables are declared in C++, their value is unknown until they are assigned one for the first time. A variable can, however, have a specific value from the moment it is declared. This is referred to as the variable’s initialization.
In C++, you can initialize a variable in 3 different ways
- C like Initialization
- Constructor Initialization
- Uniform Initialization
The word variable comes from the fact that a variable’s value can be modified.
C like Initialization
For example, to declare an int variable called id and initialise it to two from the moment it is declared, we can write:
int id = 2;
Constructor Initialization
This type of initialization encloses the initial value between parentheses.
int id(0);
Uniform Initialization
This initialization is similar to that of the constructor initialization but this one uses curly braces {} for initialization.
int id{0};
You can use any of the above initialization method for the variables in your C++ program.
A variable’s type must be known at compile time in C++, and it cannot be altered without recompiling the program. This means that an integer variable can only contain integers. You’ll need to use a new variable if you wish to store something else.
Constants in C++
We can build variables in C++ that cannot be modified. The const keyword is used for this. Here’s an illustration:
const int PI = 3.14; PI = 75 // This will result in an error.
In the above example, we have declared a constant called PI of type integer and is initialized to value 3.14. You can only initialize the constant type during its declaration. when we try to change the value of the constant, you’ll see an error.