Note that there are some explanatory texts on larger screens.

plurals
  1. POLogical AND + assignment in c++, safe?
    primarykey
    data
    text
    <p>I just learned this great pattern (from javascript actually) and I would like to apply it to my c++ code.</p> <p>To explain the pattern, let's say I am representing a string as a linked list of these:</p> <pre><code>struct link_char; struct link_char { link_char * next; char code; }; </code></pre> <p>Note that the last character of any link_char string will always have code==0. This property means that I can check for a value in the string, while using &amp;&amp; short-circuiting to prevent NULL pointer access.</p> <pre><code>bool equals_hello( const link_char * first_char ) { const link_char * c = first_char; return c-&gt;code=='h' &amp;&amp; (c=c-&gt;next)-&gt;code=='e' &amp;&amp; (c=c-&gt;next)-&gt;code=='l' &amp;&amp; (c=c-&gt;next)-&gt;code=='l' // if string == "hel", we short-circuit here &amp;&amp; (c=c-&gt;next)-&gt;code=='o'; } </code></pre> <p>My question is about safety, not readability. I know the short-circuiting will work as long as &amp;&amp; is not overloaded. But will the assignment operations happen in the right order, or is it implementation defined?</p> <p>The above example is explicit about where reads/writes can happen, but I would also like to use this pattern in situations where there can be side-effects. For example:</p> <pre><code>// think of these as a bunch of HRESULT type functions // a return value of 0 means SUCCESS // a return value of non-zero yields an Error Message int err; ( !(err=initialize()) &amp;&amp; !(err=create_window()) &amp;&amp; !(err=run_app() ) || handle_error(err); </code></pre> <p>Will these kinds of operations work as intended cross-platform? I've read that "if you read a variable twice in an expression where you also write it, the result is undefined". But intuitively I feel like the short-circuiting guarantees the order, does it not?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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