Thursday, September 22, 2011

array initialization in c and c++


Array Initialization
We can Initilize an Array when it is declared. Initializers are constant values/expressions seperated by a comma and enclosed within flower braces {} as below:

dataType variableNameOfArray[no_elements] = {values}

int employee[5] = {120, 121, 122, 123, 124};
As a convinience, if you leave out the size of the array, it creates it with the exact size to hold that number of initial values.

int employee[] = {120, 121, 122, 123, 124};
The elements in the aggregate that are not given initilizers are default initialized according to their data type.
The code
/*
 * c++ example
 */

#include <iostream.h>

using namespace std; 

int main() {
  int array[5]={1,2};
  unsigned int i;
  cout << "\nInitilization of rest of the elements\n";
  for(i=0; i<5; ++i){
    cout << "Array[" << i << "]" << array[i] << endl;
  }
}
/*
 * Output
 */
 Initilization of rest of the elements
 Array[0]1
 Array[1]2
 Array[2]0
 Array[3]0
 Array[4]0

*/

In this code, only the array index 0 and 1 are initilized with values 1 & 2, whereas rest of the elements in the array will be initilized with zeros.

Also, We can initialize all the elements of an integer Array with 0 value by assigning with empty {} as below:

int array[5] = {};

Array Initilization in a class
Arrays are always initilized outside the class. Usually static const data types are initilized inside the class declaration, but, static const Arrays are also initilized outside the class declaration as below:

#include <iostream.h>

using namespace std; 

class
Abc {
  static const int arr[3];
  static const double var = 3.14;

  public: Abc()
          {
            for(int i=0; i<3; ++i)
            {
              printf("%d", arr[i]);
            }
          }
};

const int Abc::arr[3] = {1,2,3};

int main()
{
  Abc aa;
  return(0);
}
/*
 * Output
 *
 123
 */


Special Cases in array inityialization:
1. Elements with missing values will be initialized to 0:


int myArray[10] = { 1, 2 }; //initialize to 1,2,0,0,0...


2. This will initialize all elements to 0:


int myArray[10] = { 0 }; //all elements 0


3. objects with static storage duration will initialize to 0 if no initializer is specified:


static int myArray[10]; //all elements 0
 
 
 

No comments:

Post a Comment