Sunday, September 19, 2010

Pointer Semantics Vs Value Semantics

Value semantics means we directly deal with the values and we pass copies of that value around. We can say that nobody will change the value.

However, in pointer semantics we deal with pointer, and anyone can change the value at the pointer location.

Consider the following program.

/*
 * main.c
 *
 *  Created on: Sep 18, 2010
 *      Author: administrator
 */

#include

void f (int * p, int * q) {
p = q;
*p = 2;
}

int i = 0, j = 1;


int main ( )
{
f(&i, & j);
printf("%d %d\n", i, j) ;
return 0;
}

The result will be 0 and 2. Why? Let me explain it to you.

We have two global variable i and j and we pass the pointer of these two variables to the function f.  When we do p = q, we actually loose the reference of i, and we get two pointers namely p and q both pointing to j. then when we do * p = 2, we actually change the value of j to 2. 

The whole thing can be depicted by the following diagram...



However, as we lost the reference of i in the step p = q, in the main program, the value of i that gets printed is the global variable that is 0. Hence we get the result as i = 0 and j = 2.

Hope this explains the pointer arithmetic to my students...

No comments: