Declaration and initialization

In C++, declaration and initialization are fundamental steps in working with variables. Understanding how to properly declare and initialize variables is essential for writing effective C++ programs. Here’s a detailed explanation:

Declaration

Declaration is the process of specifying a variable’s type and name. This tells the compiler that a variable with a certain name and type exists.

Syntax:

type variableName;

Example:

int age;
float salary;
char grade;

Initialization

Initialization is the process of assigning an initial value to a variable. This can be done at the time of declaration or later in the code.

Initialization at Declaration

You can initialize a variable at the time of declaration. This ensures the variable starts with a known value.

Syntax:

type variableName = initialValue;

Examples:

int age = 25;
float salary = 50000.50;
char grade = 'A';

Separate Initialization

You can also declare a variable first and then initialize it later in the code.

Example:

int age;
age = 25;

float salary;
salary = 50000.50;

char grade;
grade = 'A';

Types of Initialization

Copy Initialization

int a = 10;
double b = 3.14;

Direct Initialization

int a(10);
double b(3.14);

List Initialization (C++11 and later)

int a{10};
double b{3.14};

Default Initialization

When variables are declared without explicit initialization, their values depend on their storage duration:

Automatic (Local) Variables

void foo() {
    int x; // Undefined value
}

Static Variables

static int x; // Initialized to 0

Global Variables

int x; // Initialized to 0

Constant Initialization

You can declare and initialize constants using the const keyword. Constants cannot be modified after initialization.

Example:

const int maxAge = 100;
const float pi = 3.14159;