increment operator

I am for the moment studying classes and i have an example that throws me for a loop. Being in the learning phase i encounter problems relative to things i thought i knew!!
So here goes, i cut the example to spare time and space.
We are in the beginning of main()

int i, index = 0;
int ary[10];
void aryput 9 int i) {
if (index == 10){
cout << "Array is full: "
return:
}
index++;
ary[index] = i;
}

//call the funct. aryput twice

aryput(10);
aryput(20);

By my understanding: the ist time aryput is called
index is incremented to 1
and aryput[1] = 10

The 2nd time aryput is called index is again incremented to 2
so aryput[2] = 20

I expected elements 0 and 1 of the array (ary) would be initialized!!!

I would have reversed the last two statements in the funct. aryput
writing:

ary[index] = i;
index++;

This prompts another question:
thru the 1st call to the funct. aryput an element of the array is initialized:
are the other elements of the array then automatically initialized to 0??

First thing's first. I would highly recommend you place all code inside code tags to preserve readability. They'll be at the right of your screen, with a button that looks like "<>".

Arrays of n size are automatically initialized to 0 in all indices, unless you initialize them to something else explicitly. BUT here's the kicker. You need brackets; otherwise you get trash values for what's being inserted into your array. In other words,

int arr[5]; // when you std::cout the elements inside, you get trash values

int arr[5] = {}; // when you std::cout, you get all 0's
Last edited on
Topic archived. No new replies allowed.