Variable Declaration and Initialization
In C++, variable declaration and initialisation are fundamental concepts. Here’s a concise to explanation along with examples to illustrate them:
Variable Declaration
Declaring a variable means informing the compiler about the variable's name and type, but it doesn't allocate its name and type, nor does it allocate memory or assign a value.
Syntax:
type variable_name;
Example:
int age;
float height;
char grade;
Variable Initialization
Initializing a variable means assigning it an initial value at the time of declaration. This allocates memory and assigns the value.
Syntax:
type variable_name = value;
Example:
int age = 25;
float height = 5.9;
char grade = 'A';
Combining Declaration and Initialization
You can combine declaration and initialization in a single statement, which is a common practice.
Example:
int age = 25;
float height = 5.9;
char grade = 'A';
Multiple Variables
You can declare and initialize multiple variables of the same type in one line.
Example:
int x = 10, y = 20, z = 30;
Constant Variables
You can declare constant variables that cannot be changed after initialization using the const keyword.
Example:
const int MAX_AGE = 100;
const float PI = 3.14159;
Different Types of Initialization
C++ offers various ways to initialize variables, including:
Copy Initialization:
int age = 25;
Direct Initialization:
int age(25);
Uniform Initialization (C++11 and later):
int age{25};
Example Code
Here’s a complete example demonstrating different types of variable declarations and initializations:
#include <iostream>
int main() {
// Declaration
int age;
float height;
char grade;
// Initialization
age = 25;
height = 5.9;
grade = 'A';
// Declaration and Initialization
int weight = 70;
float bmi = 22.5;
char initial = 'J';
// Constant variables
const int MAX_AGE = 100;
const float PI = 3.14159;
// Direct Initialization
int year(2024);
// Uniform Initialization
int month{8};
std::cout << "Age: " << age << std::endl;
std::cout << "Height: " << height << std::endl;
std::cout << "Grade: " << grade << std::endl;
std::cout << "Weight: " << weight << std::endl;
std::cout << "BMI: " << bmi << std::endl;
std::cout << "Initial: " << initial << std::endl;
std::cout << "Max Age: " << MAX_AGE << std::endl;
std::cout << "PI: " << PI << std::endl;
std::cout << "Year: " << year << std::endl;
std::cout << "Month: " << month << std::endl;
return 0;
}
This example covers variable declaration, initialization, and the use of constants, demonstrating different methods of initializing variables in C++.