Search code examples
c++stringresizeassign

Why doesn't C++ like this syntax for strings?


name_abbreviation = name_last.resize(2);

Here I have to assign first

name_abbreviation = name_last;

Then

name_abbreviation.resize(2);

Would like to kindly ask you if you could explain me why the other way doesn't work?


Solution

  • Because due to operator precedence this code:

    name_abbreviation = name_last.resize(2);
    

    is equal to:

    name_abbreviation = (name_last.resize(2));
    

    and is logically equal to:

    auto tmp = name_last.resize(2);
    name_abbreviation = tmp;
    

    which is not compilable as std::string::resize() returns nothing and even if it would compile it would not do what you want.

    What you want to do can be achieved by:

    (name_abbreviation = name_last).resize(2);
    

    but this not quite readable code. I, personally, would prefer 2 separate statements.

    Note the same result can be achieved by much simpler code:

    name_abbreviation = name_last.substr( 0, 2 );
    

    which can be also more efficient on some implementations.