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.
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: 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.
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? ^_^
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.