Pointer arithmetic doubt in output

Please explain the output of the last line of the code. Why 3a when short is of 2 bytes? The output is :
1
2
3
4
0x23fe34

0x23fe36
0x23fe3a  0x23fe36 0x23fe3a

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main()
{
short num=77;
short* sptr = &num;
cout<<"Pointer to short"<<endl;
cout<<sptr-1<<endl<<endl;	
cout<<sptr<<endl;
cout<<++sptr<<" "<<sptr++<<" "<<sptr<<endl;
}
Last edited on
In line 11, the order in which those prefixes and postfixes are applied is undefined. It can do whatever it likes.

Try this instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;
 
int main()
{
short num=77;
short* sptr = &num;
cout<<"Pointer to short"<<endl;
cout<<sptr-1<<endl<<endl;	
cout<<sptr<<endl;
cout<<++sptr<< endl;
cout <<sptr++<< endl;
cout <<sptr<<endl;
}


You've learned that if you're applying prefixes and postfixes, don't do it all at once. This, for example, is similarly undefined:

a = ++b + b++;
Don't do it. You don't know what will happen.
Ok Understoood.
Topic archived. No new replies allowed.