Note that there are some explanatory texts on larger screens.

plurals
  1. PODifference between the * and & operator in function calls
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/670101/c-functions-ampersand-vs-asterisk">C++ functions: ampersand vs asterisk</a><br> <a href="https://stackoverflow.com/questions/9636903/what-are-the-distinctions-between-the-various-symbols-etc-combined-with-p">What are the distinctions between the various symbols (*,&amp;, etc) combined with parameters?</a> </p> </blockquote> <p>I am wondering the difference between the address operator <code>&amp;</code> and the deference operator <code>*</code> in a C++ function call. For example take the following function</p> <pre><code>void foo (std::string&amp; param) { param = "Bar."; std::cout &lt;&lt; param.size(); } </code></pre> <p>and let's call it in our <code>main()</code> function like so...</p> <pre><code>int main() { std::string test; foo(test); //Why not foo(&amp;test)? std::cout &lt;&lt; test; //Prints out the value "Bar." } </code></pre> <p>First off, why does the <code>&amp;</code> operator allow me to assign a value as if it were a pointer (assigning it a value that survives the RAII and scope of the function <code>foo()</code> when it's not a pointer) as it is able to be printed out in my <code>main()</code> function even though it's not <code>static</code>? I am assuming it is not a pointer because I am able to access the <code>size()</code> method by using the <code>.</code> operator instead of the <code>-&gt;</code> which is used for pointers.</p> <p>Secondly, what would be the difference between using the <code>&amp;</code> operator in a function parameter vs. using the <code>*</code> operator? Is it even different than just a plain variable like <code>std::string param</code>? It appears to be called like that (<code>foo(test)</code> instead of <code>foo(&amp;test)</code>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload