c++operator-precedenceassignmultiple-assignment

How does a C++ command with two equal signs work?


I found some code in the program I work with:

PWSTR myWchar = NULL;
WCHAR *p = myWchar = new WCHAR[4];

How would I read a line with two equal signs?

How is it computed?

A:

 myWchar  = new WCHAR[4];
 WCHAR *p = myWchar 

or B:

 WCHAR *p = myWchar ;
 myWchar  = new WCHAR[4];

Solution

  • It's option A, exactly equivalent to (with unnecessary parens):

    WCHAR *p = (myWchar = new WCHAR[4]);
    

    If myWchar had a custom operator= and/or the type of p had a custom constructor or cast from myWchar's type to p's type, this could mean p and myWchar end up slightly different from one another, but in this case, WCHAR* and PWSTR are fundamentally the same type, so they both end up assigned to the same thing, the result of the new WCHAR[4].

    In this case, it's actually the result of assignment to myWchar used as the initialization for p, but even if the structure was:

    PWSTR myWchar = NULL;
    WCHAR *p;
    p = myWchar = new WCHAR[4];
    

    so it was all assignment, no initialization, assignment is right-to-left associative, so it would occur in the same order (it just would use assignment rather than initialization semantics for the assignment to p, which could matter for custom types).