int i = 12;
i += 1; // 13
i = 55; // 55
In your example, you are creating a temporary integer variable i
and storing the value 12 in it. You are then taking the value already stored in i
(12) and adding 1 to it.
i += 1;
is the same as i = i + 1;
in your case i = i + 1
is equivalent to this math:
i = 12 + 1
You are then throwing away the value that you have just stored in i
and replacing it with 55. You have overwritten the data stored in the temporary variable i.
int x = 6;
int * y = &x;
*y += 1; // 7
*y = 91; // 91
Now, in the case of x
and y
, you x
is a temporary integer variable just like i
above.
By saying int * y = [something];
however, you are declaring a temporary integer pointer to the memory location of some integer. Usually the memory address of some variable that has already been created. Setting y equal to the address of x
sets the thing that the pointer is pointing to the location in memory of x
. Under this setup, dereferencing y (*y)
will yield the value of x
, not the address of it. If you print out y
, you will print the address of x
. If you print out *y
, you will print out the value of x
. *y += 1
yields the value of x + 1
. Setting *y
to 91 resets the value of x
, in the same way, that you have done above with i
and 55.
Allow me to demonstrate the usefulness of this pointer through an example.
Let's say you had 4 integer pointers all set to point to the address of x (&x)
. Changing the value of any one of those pointers after dereferencing them (*ptr)
will change the value stored in x and thus the value pointed to by each of the other 3 pointers you have initialized to the address of x
.
By contrast, let's say you have 4 variables (int m
, int n
, int j
, int k
) all set equal to 4. When you increment k
by 1, it will not change the value stored in m
, n
or j
. It will only change k
.