Reputation: 283
I am learning cpp on my own through a book named Programming with Cpp by John R. Hubbard, Phd. The example below is from the same source.
#include <iostream>
using namespace std;
void read(int [], int&);
void print( int [], int);
long sum (int [], int);
const int MAXSIZE=100;
int main(){
int a[MAXSIZE]={0}, size;
read (a,size);
cout << "The array has " <<size <<" elements: ";
print (a,size);
}
void read(int a[], int& n){
cout <<"Enter integers. Terminate with 0: \n";
n=0;
do{
cout << "a ["<<n<<"]: ";
cin >> a[n];
}
while (a[n++] !=0 && n<MAXSIZE);
--n; //don't count the 0
}
void print (int a[], int n){
for (int i=0; i<n; i++)
cout <<a[i]<<" ";
cout<<endl;
}
Based on the above code, I need to know:
1) Why is the array[MAXSIZE]
made equal to 0
in the main()
function? Is it ok to use it without initializing it?
2) What is the role of n=0
in the read()
function?
Upvotes: 2
Views: 85
Reputation: 2982
1) Why is the array[MAXSIZE] made equal to 0 in the main() function? Is it ok to use it without initializing it?
Only the first element is set to 0
.The others are default initialized to 0
. In this case is would be ok to use it without initializing it, that is, even without the ={0}
, but only if valid integers are provided.
2) What is the role of n=0 in the read() function?
The variable n
is used to index through the parameter array a
. Since C++ uses zero based indexing the first element of an array is at position 0
, and that's why n
is set to 0
initially.
Upvotes: 2