How do we initialize a variable in C++?



You can initialize a variable using the assignment operator or use its constructor when initializing it. For example,

int i = 0;
MyClass instance(1, "Hello");

It will be automatically initialized if

  • It's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance;
  •  You use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except the first two items: a[0] == 1 and a[1] == 2)
  •  It is a global/extern variable
  •  It is defined static
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements