C++ - Variables
In C++, variables are used to store and manipulate data. Before using a variable, it needs to be declared, which involves specifying its type and optionally providing an initial value. Here are some examples of declaring variables in C++:
Declaring an integer variable:
int age;
In this example, we declare a variable named age of type int. It doesn't have an initial value assigned yet.
Declaring and initializing a floating-point variable:
float pi = 3.14;
Here, we declare a variable named pi of type float and assign it an initial value of 3.14.
Declaring multiple variables of the same type in a single statement:
int x, y, z;
This declares three integer variables named x, y, and z. All three variables are of type int and don't have initial values assigned.
Declaring and initializing a character variable:
char grade = 'A';
This example declares a variable named grade of type char and initializes it with the value 'A'.
When you need to declare many variables in C++, you can do so in a single statement.
int a, b, c; // Declaring multiple integer variables
float x, y, z; // Declaring multiple floating-point variables
char ch1, ch2, ch3; // Declaring multiple character variables
In the above example, we declare three variables of each type (int, float, and char) in a single statement. Each variable is separated by a comma.
Declaring a constant variable:
const double gravity = 9.8;
In this case, we declare a constant variable named gravity of type double. The const keyword indicates that the value of this variable cannot be changed once assigned. It is common to use uppercase names for constant variables.