Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected output of C++

I found unexpected output of following program.

Here pointer ptr point to address of variable i and i hold the value 10. It means the value of ptr also 10. Next ptr increment once. It means now it hold value 11. But in the following program ptr prints 12.

#include <iostream>
using namespace std;    

int main()
{
    int i = 10;
    int *ptr = &i;
    int j = 2;
    j += *ptr++;

    cout<<"i : "<<i<<"\n";
    cout<<"j : "<<j<<"\n";
    cout<<"ptr : "<<*ptr<<"\n";
}

Output:

i : 10
j : 12
ptr : 12

So I don't understand why ptr prints 12 instead of 11?

like image 269
msc Avatar asked Oct 25 '19 13:10

msc


1 Answers

The program has undefined behavior.

This statement

j += *ptr++;

is equivalent to

j += *( ptr++ );

So the pointer now points to after the variable i that is it does not point to a valid object.

Thus this statement

cout<<"ptr : "<<*ptr<<"\n";

invokes undefined behavior.

It happened such a way that the compiler placed the variable j after the variable i. However the order of the variables is unspecified by the C++ Standard.

For example the gcc compiler's output is the same as you showed.

i : 10
j : 12
ptr : 12

While the clang compiler's output is

i : 10
j : 12
ptr : 4201824

What you mean is the following

j += ( *ptr )++;

In this case the output will be

i : 11
j : 12
ptr : 11

Pay attention to that the outputted value of i is 11 because the variable i is outputted in the following sentence when the side effect was already applied to the variable.

like image 54
Vlad from Moscow Avatar answered Nov 12 '22 10:11

Vlad from Moscow