Pre/Post Increment Operator

Q1:

1
int arr[] = {10, 20, 30, 40, 50, 60};
2
int* ptr = arr;
3
*(ptr++) += -1; // 9, 20, 30, 40, 50, 60
4
*(++ptr) += -2; // 9, 20, 28, 40, 50, 60
5
ptr += 2;
6
*ptr += -3;// 9, 20, 28, 40, 47, 60
Copied!

Ans:

9, 20, 28, 40, 47, 60

Demo:

1
#include <stdio.h>
2
3
int main(){
4
int arr[] = {10, 20, 30, 40, 50, 60};
5
int* ptr = arr;
6
*(ptr++) += -1; // 9, 20, 30, 40, 50, 60
7
*(++ptr) += -2; // 20, 20, 28, 40, 50, 60
8
ptr += 2;
9
*ptr += -3;// 20, 20, 40, 40, 47, 60
10
11
for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){
12
printf("arr[%d] = %d \n", i, arr[i]);
13
}
14
15
return 0;
16
}
17
Copied!

Explanation:

int* ptr = arr;

1
ptr V
2
arr[] = {10, 20, 30, 40, 50, 60};
Copied!

*(ptr++) += -1;

++在 ptr 後面, 他會先賦值再移動指標 Step 1. *ptr --> 10 Step 2. *ptr = *ptr + (-1) --> arr[0] = 9 Step 3. ptr++ --> this pointer has shifted to arr[1]

*(++ptr) += -2;

++在 ptr 前面, 他會先移動再賦值 Step 1. ++ptr --> this pointer has shifted to arr[2] Step 2. *(++ptr) == arr[2] = 30 Step 3. *(++ptr) = *(++ptr) + (-2) --> arr[2] = arr[2] -2 --> arr[2] = 28

ptr += 2

ptr += 2 --> this pointer has shifted to arr[4]

*ptr += -3

*ptr += -3 --> arr[4] = arr[4] -3 --> arr[4] = 47

Summary:

1
(1)
2
a = ptr++
3
ptr的值先給 a, ptr再加 1
4
5
a = ++ptr
6
ptr先加 1, ptr的值再傳給 a
7
8
9
(2)
10
*(ptr++)
11
++在 ptr 後面, 他會先賦值再移動指標
12
13
*(++ptr)
14
++在 ptr 前面, 他會先移動再賦值
Copied!
Copy link