tailieunhanh - A Complete Guide to Programming in C++ part 21
A Complete Guide to Programming in C++ part 21. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | PASSING ARGUMENTS 179 Passing by Value Passing values to a function when the function is called is referred to as passing by value. Of course the called function cannot change the values of the arguments in the calling function as it uses copies of the arguments. However function arguments can also be passed by reference. In this case the function is passed a reference to an object as an argument and can therefore access the object directly and modify it. An example of passing by reference was provided in the example containing the function time . When time sek is called the address of the variable sek is passed as an argument allowing the function to store the result in the variable. We will see how to create functions of this type later. Passing by value does however offer some important advantages function arguments can be any kind of expression even constants for example the called function cannot cause accidental modifications of the arguments in the calling function the parameters are available as suitable variables within the functions. Additional indirect memory access is unnecessary. However the fact that copying larger objects is difficult can be a major disadvantage and for this reason vectors are passed by reference to their starting address. Local Objects The scope of function parameters and the objects defined within a function applies only to the function block. That is they are valid within the function only and not related to any objects or parameters of the same name in any other functions. For example the program structure opposite contains a variable a in the function func1 and in the function func2 . The variables do not collide because they reference different memory addresses. This also applies to the variables x in func1 and func2 . A function s local objects are placed on the stack the parameters of the function are placed first and in reverse order. The stack is an area of memory that is managed according to the LIFO last in first out .
đang nạp các trang xem trước