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; }
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
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
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
oh. now I understand. Do you have any books on functions?
I suggest reading a good introductory book on C++, e.g., Accelerated C++.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)