Sequence point problem?

D

Dave

Hello all,

Can anybody identify any sequence point problems in the expression below?

i = (i == string::npos) ? 0 : ++i;

Thanks,
Dave
 
V

Victor Bazarov

Dave said:
Can anybody identify any sequence point problems in the expression below?

i = (i == string::npos) ? 0 : ++i;

The Standard says that between sequence points (and there are none in
this expression) a stored value of any object shall be modified at most
once. If the expression in the parentheses yields false, 'i' will be
modified twice, once by ++ and the other time with the assignment, which
causes undefined behaviour. If you rewrite this as

i = (i == string::npos) ? 0 : i + 1;

there would be no problem.

V
 
J

Jack Klein

The Standard says that between sequence points (and there are none in
this expression) a stored value of any object shall be modified at most
once. If the expression in the parentheses yields false, 'i' will be
modified twice, once by ++ and the other time with the assignment, which
causes undefined behaviour. If you rewrite this as

i = (i == string::npos) ? 0 : i + 1;

there would be no problem.

There is a sequence point in this expression, at the '?' after the
condition has been evaluated but before the evaluation of the chosen
predicate expression.

But your reasoning and correction are right.
 
V

Victor Bazarov

Jack said:
There is a sequence point in this expression, at the '?' after the
condition has been evaluated but before the evaluation of the chosen
predicate expression.

Thank you for the correction, Jack. So, even though there is a SeqP in
that expression, ++i would be evaluated *after* it, right? Which still
makes this essentially the same as

if (i == string::npos)
i = 0;
else
i = ++i; // undefined behaviour

V
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top