Can anyone tell me how to pass on parameters to a function?
This is a discussion on Passing on parameters within the C++ Programming forums, part of the General Programming Boards category; Can anyone tell me how to pass on parameters to a function?...
Can anyone tell me how to pass on parameters to a function?
a will 0, but not 10. And the book says that it has something to do with passing parameters.Code:void F(int a) { a = 10; } int main(int argc, char* argv[]) { int a = 0; F(a); cout << a << endl; }
you pass the parameter by value - it means any changes to vaariable inside the function are not visible outside.
If you want to see the changes - you need to pass it by reference
or just return the result...Code:void f(int& val) { val = 10; } int main() { int a = 0; f(a); std::cout << a << std::endl; return 0; }
If I have eight hours for cutting wood, I spend six sharpening my axe.
Oh, can you just explain to me how the parameters passed by value in the example? The book says that a copy of the parameter has been made. But I don't understand.
It is just like it says -
when main is started the automatic variable a is allocated on stack and its vaue is set to 0Code:int f(int val) { val = 10; } int main() { int a = 0; f(a); return 0; }
when f is going to start another automatic varible - I even have given it different name - val is allocated on the stack
and the value of a is copied to this new location - it is called passing parameters by value.
all changes that f makes to this new variable do not affect in any way the original variable a.
So when f is finished - the value of a is left intact
If I have eight hours for cutting wood, I spend six sharpening my axe.
oh. now I understand. Do you have any books on functions?
I suggest reading a good introductory book on C++, e.g., Accelerated C++.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
But, is it good to read as many books as possible?
Yes, if they are good books, but trying to read them simultaneously will probably be problematic for you.Originally Posted by Allen
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way