PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How call by reference work in c++?

 July 06, 2022     c++, pass-by-reference     No comments   

Issue

Consider the following function prototype:

swap(int &a,int &b);

'x' and 'y' are two integers local to main function. Assume that the control is in main() function. Now,when the compiler encounters this type of statement:swap(x,z); What does actually happen underneath the hood(I mean,in terms of memory locations)? My questions are:-

  1. Is there any memory allocated for a,b in swap() function's stack?If allocated ,what would it store?
  2. How does call by references work?

Solution

Is there any memory allocated for a,b in swap() function's stack?If allocated, what would it store?

First, consider the answer to the same question in a call to swap_ptr(int *a, int *b) Assuming that stack is used for passing parameters, some memory would be allocated to a and b in a call to swap_ptr(&x, &y). That memory would hold pointers to x and y.

The same thing happens when you pass references: some memory is allocated on the stack to pass references a and b, and initialized with references to x and y. This memory often has layout identical to a pointer, but the standard does not require this: the structure used for passing references is implementation-specific and non-transparent.

How does call by references work?

In the same way that call by value works, except the compiler knows to construct a reference, rather than making a copy of the object being passed.



Answered By - Sergey Kalinichenko
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing