LIT
LIT

Reputation: 73

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?

Upvotes: 0

Views: 104

Answers (2)

Slava
Slava

Reputation: 44258

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.

Upvotes: 5

asmmo
asmmo

Reputation: 7100

resize() function doesn't return a thing. It changes the size of allocated memory of the string it use on it. So to assign a string to another just use

name_abbreviation = name_last;

using the operator = will make the string on the L.H.S. have the same size of the string on the right and have the same characters..

Upvotes: 1

Related Questions