Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I searched this site for similar question but none dealt with this in-depth. I'm sorry if this is the most overused question ever in this site. But this piece of code is very puzzling.

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
int a[3];
cout<<"Enter number to be inserted: "<<endl;
int num;//Value that is intended to be inserted in a[0].
int index;//To keep track of array index.
cin>>num;

cout<<"Postincrement"<<endl;
index=-1;
a[index++]=num;
cout<<a[index]<<endl;
cout<<index<<endl;

cout<<"Preincrement"<<endl;
index=-1;
a[++index]=num;
cout<<a[index]<<endl;
cout<<index<<endl;
}


What I have tried:

3
Postincrement
-606760192
3
Preincrement
3
0

Preincrement works perfectly. Element is inserted in the a[0] and index is 0.

I don't get why the value of the index becomes the number(3 in this case) on post increment. Shouldn't num be inserted inside the array (a[0]).How could the number be assigned to the index when it's been specified clearly that a[index++]=num. Can anybody help me understand this better?
Posted
Updated 30-Aug-20 19:34pm
v2

In
a[index++]=num;
a is first indexed by index, that cell is set to num, and finally index is incremented.

In
a[++index]=num;
index is first incremented and then used as the index for the cell that is set to num.

This means that your first assignment is actually
a[-1]=num;
after which a[0] still contains random junk: -606760192 in this case. Not only that, but assigning to a[-1] will usually corrupt memory or cause your program to immediately crash in a debug build that includes array bounds checking.
 
Share this answer
 
v3
Comments
Espen Harlinn 30-Aug-20 21:14pm    
or it may continue to execute in a corrupted state, and that could be even worse. :-)
Greg Utas 30-Aug-20 21:25pm    
Definitely worse. A trampler is a fearful bug because the problem seldom shows up until long after the criminal has left the scene. :)
CPallini 31-Aug-20 2:13am    
5.
Kohila G 31-Aug-20 9:53am    
Thanks for the clarification.
To add to what Greg says, you start with an index of -1, which means that your first assignment is placed outside the array. Since both index and a are created on the stack, the memory you are accessing is probably part of the return address for the main function. That's going to cause your app to do strange things at the best of times, or will be detected by bound checking code.

Have a look here: Why does x = ++x + x++ give me the wrong answer?[^] - it tries to explain pre- and post-increment and may help you see what is going on.
 
Share this answer
 
Comments
Kohila G 31-Aug-20 9:52am    
Thanks for the clarification.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900