0

Please explain the output of the last line of the code. Why 0x23fe3a when short is of 2 bytes? And why 0x23fe36 after 0x23fe3a? The output is :

0x23fe34

0x23fe36

0x23fe3a 0x23fe36 0x23fe3a

#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;
    }

But If I break the last line into two lines as below, I get the correct output. which is

0x23fe34

0x23fe36

0x23fe38 0x23fe38 0x23fe3a

cout<<++sptr;
cout<<" "<<sptr++<<" "<<sptr<<endl;

Why is it happening?

Shivam
  • 1
  • 1
  • 1
    Note that incrementing or decrementing a pointer to a single element is undefined behavior. – François Andrieux Sep 25 '17 at 18:14
  • No. This appears to be something else – Shivam Sep 25 '17 at 18:14
  • Define "correct". – YiFei Sep 25 '17 at 18:15
  • But why, when we break the last line into 2 lines, it gives correct output? – Shivam Sep 25 '17 at 18:15
  • I have edited the question to show correct output – Shivam Sep 25 '17 at 18:18
  • 2
    @Shivam The example is full of undefined behavior. The fact that you get what appears to be correct output is merely a question of luck. The behavior could change at any time for no apparent reason. You should read about [undefined behavior](http://en.cppreference.com/w/cpp/language/ub). – François Andrieux Sep 25 '17 at 18:19
  • You have the UB there. This ridiculous question was asked here last week at least 10 times. You can't have more than one of those operators in one statement. Read the comments and do not argue. – 0___________ Sep 25 '17 at 18:22
  • Can you please give me a link of a source where undefined behaviour related to pointers is explained in a simple language – Shivam Sep 25 '17 at 18:27
  • From http://en.cppreference.com/w/c/language/operator_arithmetic#Pointer_arithmetic while referring to adding an integer to a pointer or subtracting an integer from a pointer : *"The behavior is defined only if both the original pointer and the result pointer are pointing at elements of the same array or one past the end of that array. Note that executing p-1 when p points at the first element of an array is undefined behavior and may fail on some platforms."* – François Andrieux Sep 25 '17 at 18:36

0 Answers0