Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you're doing wrong is assuming that that functions in a &lt;&lt; expression evaluate in left-to-right order. They don't necessarily. And in this case your compiler is evaluating them right to left.</p> <p>(To clarify, since the original question didn't say, the behavior he's seeing is that it's printing out:</p> <pre><code>1 98 do </code></pre> <p>instead. (Or at least, that's what I assume because that's what I get when I compile it with g++)</p> <p>What's happening is that the expressions on either side of an operator both have to be run before the operator, but they can be run in either order. For whatever reason, in this case, your compiler is running the rightmost call to searchValue first and then the middle one and then the left one. Since searchValue changes s, this, of course, changes the answer.</p> <p>You might think that the code you wrote is guaranteed to give you the same answer as:</p> <pre><code> string s="&lt; feature token = \"do\" id = \"98\" freq = \"1\" /&gt;"; string x = searchValue(s,'\"'); string y = searchValue(s,'\"'); string z = searchValue(s,'\"'); cout &lt;&lt; x &lt;&lt; endl &lt;&lt; y &lt;&lt; endl &lt;&lt; z &lt;&lt; endl; </code></pre> <p>but it isn't, and, at least in this particular case, it doesn't. If you run that code, you'll see that it gives you the expected result. Your code is running as if it were written like this:</p> <pre><code> string s="&lt; feature token = \"do\" id = \"98\" freq = \"1\" /&gt;"; string z = searchValue(s,'\"'); string y = searchValue(s,'\"'); string x = searchValue(s,'\"'); cout &lt;&lt; x &lt;&lt; endl &lt;&lt; y &lt;&lt; endl &lt;&lt; z &lt;&lt; endl; </code></pre>
 

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