Computers |
|
| | #1 (permalink) |
| Newb Techie Join Date: Oct 2004
Posts: 14
| Could someone help me with this. Passed by value would be the result i get from actually running this program right? But I am confused about the passed by reference. Can anyone solve this and explain how you got your answers. Thanks ![]() void foo(int x, int y) { i = y; y += 3; } void main() { i = 2; j = 3; foo(i, j); printf("%d %d\n", i, j); } what would the output be if you: passed by value: passed by reference: and passed by value-result: thanks ![]() |
| | |
| | #2 (permalink) |
| Ultra Techie | Yup, the above program is pass by value. If you want to make a 'pass by refernce call'' pass the address of variable 'i' and 'j' [ foo(&i,&j) ] and the arguments in the function should be declared as pointers [ void foo{int *x,int *y) ] and manipulate the variables inside the function 'foo' accordingly. Sign Intercodes |
| | |
| | #5 (permalink) |
| True Techie Join Date: Apr 2004
Posts: 168
| The difference is that if you pass by value only the value of i changes as y is a private variable in the function foo. However if you pass by reference both values change as the function is working with the variables i and j. To be strict C is always pass by value, the use of the & symbol sort of simulates pass by reference as the compiler uses pointers to memory locations, but that is sort of pedantic. Pointers should be used though because they help conserve memory space, ie. the pass by reference method only uses half the memory allocation of the pass by value for it's variables. They are also vital for the implementation of dynamic memory allocation.
__________________ -------------------- Nak Is it just me, or does something smell suspicious about all this? |
| | |
| | #7 (permalink) |
| True Techie Join Date: Apr 2004
Posts: 168
| errr, quick brush up on my 'C' later.... yes it is, though I can't remember my printf formatting too well so I am assuming that bit is right. But the pointer stuff is. & passes the address of the variable hence the statement, p = &c, assigns the address of 'c' to the variable 'p' * is called the indirecton operator and when applied to a pointer it accesses the variable the pointer points to. Hence d = *p would assign the value of 'c' in the above example to 'd' You code is totally consistent with this therefore it's right.
__________________ -------------------- Nak Is it just me, or does something smell suspicious about all this? |
| | |
| | #8 (permalink) |
| True Techie Join Date: Apr 2004
Posts: 168
| Sorry, I should also add that you have declared the fuction foo properly by indicating that the values passed are pointers. Too easy to forget that one...
__________________ -------------------- Nak Is it just me, or does something smell suspicious about all this? |
| | |