Cpp - Introduction Variable Initialization

Introduction

A variable can be initialized, i.e. a value can be assigned to the variable, during its definition.

Initialization is achieved by placing the following immediately after the name of the variable:

  • an equals sign ( = ) and an initial value for the variable or
  • round brackets containing the value of the variable.

For Examples:

char c = 'a'; 
float x(1.875F); 

Demo

// Definition and use of variables 
#include <iostream> 
using namespace std; 

int gVar1;                 // Global variables, 
int gVar2 = 2;             // explicit initialization 

int main() //from   w  ww . j  ava 2 s . c o  m
{ 
    char ch('A');  // Local variable being initialized 
                   // or:  char ch = 'A'; 

    cout << "Value of gVar1:    " << gVar1  << endl; 
    cout << "Value of gVar2:    " << gVar2  << endl; 
    cout << "Character in ch:   " << ch     << endl; 

    int sum, number = 3; // Local variables with 
                              // and without initialization 
    sum = number + 5; 
    cout << "Value of sum:      " << sum  << endl; 

    return 0; 
}

Result

Any global variables not explicitly initialized default to zero.

The initial value for any local variables not explicitly initialized will have an undefined initial value.

Related Topic