Sunday, July 12, 2009

Question on call by reference?

in c call by reference is done by pointers explain how exectly memorey locations are called by reference by pointers

Question on call by reference?
Pointers are just special variables, which stores address rather than just normal values.





For any kind of variable compiler stores info about attributes and values (includes datatype, addr ... ) in a table like datastructure which is specific to compiler.





In case of call by reference u actually pass the addr rather than just value of variable.





let us say :


{


int a=2,*b;


b=%26amp;a;


f(%26amp;a); //f(b)








}


f(int *c) { *c=5; }


g(int d) { d=6;}








before proceeding first u need to understand what


"x=8; " this statement does.


It just finds the x's address by looking at the variable table and


then in that memory location the value is updated with 8.








Now coming to our example....


If you observe carefully, the function f() is accepting the address rather than value of variable. So all the updations will happen on the original location.


where as incase of g() it just updates the local variable.
Reply:Memory locations cannot be called by reference as far as I know about programming with the C language.





To be correct, C implements only one way of function call. It is call by value. In call by value, a copy of each of the argument is created locally in the invoked function. When you pass a pointer (in C, that is,), _a copy_ of that pointer is created locally in the called function.





The symbol table is used to decide whether dereferecing has to be used on a variable. That is, symbol table has details like whether a variable is a plain variable or a pointer to something.





In the case of a pointer, the value stored in that variable is treated as an address in the memory. Accordingly, relevant dereferencing instructions are generated.
Reply:A reference is an indirect pointer that doesn't look like a pointer and isn't addressed as such. All addressing is done by the compiler.





Example:





void AnswerToEverything(int%26amp; iAnswer)


{


iAnswer = 42;


}





void main(int argc, char* argv[])


{


int i = 0;





AnswerToEverything(i);





/* The value of the variable i is now 42 */


printf("%d\n", i);


}








Same example with pointers:





void AnswerToEverything(int* piAnswer)


{


*piAnswer = 42;


}





void main(int argc, char* argv[])


{


int i = 0;





AnswerToEverything(%26amp;i);





/* The value of the variable i is now 42 */


printf("%d\n", i);


}


No comments:

Post a Comment