Logical AND + assignment in c++, safe?

Viewed 1792

I just learned this great pattern (from javascript actually) and I would like to apply it to my c++ code.

To explain the pattern, let's say I am representing a string as a linked list of these:

struct link_char;
struct link_char
{
   link_char * next;
   char code;
};

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 && short-circuiting to prevent NULL pointer access.

bool equals_hello( const link_char * first_char )
{
    const link_char * c = first_char;

    return       c->code=='h' 
    && (c=c->next)->code=='e' 
    && (c=c->next)->code=='l' 
    && (c=c->next)->code=='l' // if string == "hel", we short-circuit here
    && (c=c->next)->code=='o';
}

My question is about safety, not readability. I know the short-circuiting will work as long as && is not overloaded. But will the assignment operations happen in the right order, or is it implementation defined?

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:

// 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()) && !(err=create_window()) && !(err=run_app() )
    || handle_error(err);

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?

2 Answers
Related