Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   HELP with C (http://www.go4expert.com/forums/help-with-c-t17814/)

Alex C.phoenix 1Jun2009 21:06

HELP with C
hi, masters, I've a beginner with C, here I encountered a problem, and hope someone can help me understand it:

Why the following codes is wrong:

void swap(int x, int y) /* WRONG */
int temp;
temp = x;
x = y;
y = temp;

The book gives the explanation as: "Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function." but I cannot quite understand it.


SaswatPadhi 1Jun2009 21:17

Re: HELP with C
Look, when you pass x and y to swap; what you are actually doing is : you are creating temporary copies of x and y and pass them to swap.
So, obviously your original variables are not altered 'cuz they are not involved in the operations inside the func. The func only receives two values that are copies of the originals, NOT the originals themselves.

Unfortunately C does not support call-by-reference.
But you can simulate it this way :wink:
Code: C

void swap(int *x, int *y)
      int temp;
      temp = *x;
      *x = *y;
      *y = temp;

Hope I cleared your doubt.

BTW, it looks like this is your first post.
So, Welcome to G4EF.

And please ALWAYS post your code inside code-blocks.

Alex C.phoenix 3Jun2009 11:36

Re: HELP with C
Thank you very much!

Now I got something. Does it mean that, whenever a function calls another, it only passes copies of originals to the called function, and what the called function do does not alter the original values in the calling function. But when you use an pointer, as in your example, the called function can operate on the memmory the pointer pointing to, so that it can change the orginal values accordingly.

Am I right? ^_^

SaswatPadhi 3Jun2009 11:39

Re: HELP with C
Yes you are right ! :)

When you use pointer, copies are still passed to the function. But this time the copies are of the addresses, not of the variables themselves. What you do is you use the address to access the original variable in the memory and operate on them.

All times are GMT +5.5. The time now is 08:00.