Evaluation order for a=b

X

Xavier Decoret

Let's say I want assign a unique int id to a set of string. The
following code is pretty compact and handy:

deque<string> names; // I know there are unique

map<string,int> idMap;
for (deque<string>::const_iterator iter = names.begin();
iter != names.end();++iter)
{
idMap[*iter] = idMap.size();
}

After that I can use the idMap to retrieve the unique id of a string.

QUESTION:
---------

On my implementation, the first string has id 1. I understand that
idMap[*iter] is evaluated first so when the right hand term is
evaluated, idMap do have a size() of 1.

Can I trust this to be the case on any implementation or the order of
evalutation for an assignement is not specified?

--
+-------------------------------------------------+
| Xavier Décoret - Post Doct |
| Graphics Lab (LCS) - MIT |
| mailto: (e-mail address removed) |
| home : http://www.graphics.lcs.mit.edu/~decoret|
+-------------------------------------------------+
 
R

Ron Natalie

Xavier Decoret said:
Can I trust this to be the case on any implementation or the order of
evalutation for an assignement is not specified?
No. The order of operations in C++ is by and large unspecified.
There's nothing that requires the lhs of the assignment to be evaluated
before the right hand side or vice vera. You're going to have to introduce
a temporary variable to be safe:

int i = idMap.size();
idMap[*iter] = i;
 

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
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top