Call by address in C++Call By Address is also referred to as Call By Pointers. In this Call By Address method, the developer passes the actual arguments addresses to the formal parameters. After that, the function utilizes these addresses to access the actual arguments in the system. In other words, the function arguments are passed as address when utilizing the Call by address/Pass by address technique. The calling function passes the address of the parameters. There are pointer variables utilized in the definition of the function. The function can access and modify the actual parameters with the aid of the Call by address mechanism. In a later portion of this tutorial, we'll see an illustration of the Call by address method. Example for Call by address:Let's take an example to illustrate the Call by Address in C++. Output: Value of t inside main() = 5 In the cba() function : Value of *j = 5 Value of *j = 10 Value of t inside main() = 10 Explanation: In this example, we will illustrate the Call by address mechanism. We are calling the "cba()" function and passing the address of "t" from the "main()" function. In the function definition, we are given the address of "t" in a pointer variable, or "j". The pointer is used within the function hello to alter the value of "t" to 10. As a result, following the "cba()" function call, the value of "t" is set to 10 inside the "main()" function. Example 2:Let's take another example to illustrate the Call by Address in C++. Output: Explanation: In this example, we'll demonstrate how the Call by address method can be used to a practical issue. As an illustration, we wish to create a function that switches two variables. The real variables do not change in the caller function if we swap two variables using the Call by value approach. In this case, the Call by address approach can be applied. In this example, the "mySwap()" function is being sent the addresses of both v1 (&v1) and v2 (&v2). We are using the pointers to swap the values of these two variables inside the "mySwap()" function. As we can see in the output below, after the "mySwap()" function has been called, the real values of these variables are swapped in the "main()" method. Advantages of Call by address in C++:There are several advantages of Call by Address in C++. Some main advantages of Call by Address are as follows:
However, it's crucial to handle references and pointers carefully because if not managed properly, they can result in problems like null pointer dereferencing, memory leaks, and unwanted side effects. When selecting whether to use Call by reference or call by value in C++, we should always take the design and safety of our code into account. Next TopicChrono in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India