Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, everybody;
I found the code above. But I don't understand the out where x=3 y=4. Please help me.
Why didn't work the operations ++ when case 0 twice? And why y=4, becase I think it should be 5.

What I have tried:

C++
#include<stdio.h>

int main(){
int x=2,y=3,*ptr,i=0;
int a[9]={1,2,3,4,5,6,7,8,9};

ptr=a;
//     printf("X= %d\n",x);
//     printf("*ptr= %d\n\n",*ptr);
while(i<5)
{
    //printf("i=%d\n",i);
    switch(i%3)
    {
    case 0:
        x=*(ptr)++;
//        printf("X= %d\n",x);
//        printf("*ptr= %d\n\n",*ptr);
    break;
    case 1:
       y=++*(ptr);
//       printf("Y= %d\n",y);
//       printf("*ptr= %d\n\n",*ptr);
    break;
    default:
        break;
    }
    i++;
    printf("x = %d\ty = %d\n",x,y);
}

return 0;
}
Posted
Updated 30-Jun-20 4:39am
v2

1 solution

You are playing with two things here, neither of which I am sure you understand well.

Pre- and post-increment operations can be difficult to understand, because they are "side effect" operators: they change the value of variables without an obvious assignment.
In your case,
C++
x = *(ptr)++;
is the equivelant of saying this:
x = *ptr;
ptr = ptr + 1;
And
C++
y = ++*(ptr);
is the equivelant of this:
C++
*ptr = *ptr + 1;
y = *ptr;

The second version changes the value in the array a instead of altering the pointer itself.

Run the code through the debugger and look closely at what is happening to the values of ptr and the array and you'll see what I mean.

It might be worth a quick look here: Why does x = ++x + x++ give me the wrong answer?[^] before you start diving into complicated pre- and post- increment statements!
 
Share this answer
 
v2
Comments
goksurahsan 30-Jun-20 10:37am    
I understand pre and post-increment before. But I actually ask for this action why when i=3 post-increment didn't work for ptr. I used debugger but debeugger showed me post-increment passed
OriginalGriff 30-Jun-20 11:02am    
It worked fine. It did exactly what you told it to.
goksurahsan 30-Jun-20 10:42am    
For example I think these codes are same the before codes:

case 0:
x=*(ptr);
*ptr=*ptr+1;
//x=*ptr++;
// printf("X= %d\n",x);
// printf("*ptr= %d\n\n",*ptr);
break;
case 1:
*(ptr)=*(ptr)+1;
y=*(ptr);
//y=++(*ptr);
Richard MacCutchan 30-Jun-20 10:43am    
No, see my comment below.
Richard MacCutchan 30-Jun-20 10:43am    
Not quite. The second case is equivalent to:
y = *ptr;
y = y + 1;

ptr does not get incremented in this case.

Took me half an hour to figure it out.

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