Specify operator presedence

R

Rune Allnor

Hi all.

I have this data structure:

std::map<size_t,size_t> m;
std::map:<size_t,size_t>::iterator i;

In the test suite I want to loop through the elements and
test that the elements in the map contain the correct
values. So I do things like this:

i = m.begin();

BOOST_REQUIRE( i++->second == 0 );
BOOST_REQUIRE( i++->second == 1 );

The idea is that I investigate the scond field of *i, then increment
i.
It works with my implementation.

However, according to Stroustrup, the ++ post-increment and ->
dereference operators are at the same presedence level, so
in a different implementation the result might be different.

The only alternative I can come up with is

BOOST_REQUIRE( i->second == 0 ); ++i;

Is it possible to achieve what I want safely in one statement?

Rune
 
J

Jonathan Lee

Is it possible to achieve what I want safely in one statement?

The associativity is left to right so the compiler must
interpret i++->second as (i++)->second, which is what
you want. If you're paranoid, though, use the parentheses.

But does it even matter in this case? You either
* increment i then access the member "second" of the
return value (original i), or
* access the member "second" of i, and then increment i

It's the same thing, either way.

--Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,158
Messages
2,570,881
Members
47,414
Latest member
djangoframe

Latest Threads

Top