Sunday, August 2, 2009

What is reference operator and pointer operator?

what is reference operator in c

What is reference operator and pointer operator?
There is no reference operator in C, that's a C++ thing.





In C++, within the argument list of a function declaration or prototype, %26amp; is the reference operator, and * is the pointer operator. e.g.,





int foo(int *pointer, int %26amp;reference);





Note that in the example above, "pointer" and "reference" work almost identically, in that the called function can alter the contents of either argument, as seen by the calling function. The difference is that a pointer type must be passed by address, and dereferenced to obtain the value it points to. For reference types the compiler does that for you. e.g.,





// sets the value of first 2 args to 1


int foo(int *pointer, int %26amp;reference, int val)


{


// first arg is pointer, must use dereference operator


// to access contents


*pointer = 1;


reference = 1;


// we could assign this 10,000 times, but the


// caller will never see it, because it was passed


// by value.


val = 1;


}





int main(int argc, char **argv)


{


int i1 = 0, i2 = 0, i3 = 0;





// first arg is pointer, must use address-of operator


// to pass its address


foo(%26amp;i1, i2, i3);


// both i1 and i2 now contain the value 1


// but i3 is still 0


//...


}





(To confuse matters, %26amp; is also the address-of operator, and * is also the dereference operator, it depends on where they are used.)


No comments:

Post a Comment