side effects

A

andrew browning

does i++ have the same potential for side effects as its pre-fix
equivilent ++i? and if so, is it always dangerous to use them, as in a
for loop, or only in certain circumstances?
 
A

Alan Johnson

andrew said:
does i++ have the same potential for side effects as its pre-fix
equivilent ++i? and if so, is it always dangerous to use them, as in a
for loop, or only in certain circumstances?

Define "potential for side effects". Both ++i and i++ will increment i,
if that is what you are asking (or in the case of class types, call the
corresponding version of operator++).

Also, specify what you mean by "dangerous to use them". It is quite
common for increment operators to be used in for loops:
for (unsigned i = 0; i < 10; ++i) { // Do something }

The only dangerous use I can think of is trying to use an increment
operator in an expression where the operand is also being used for
something else:
i = ++i + 1; // unspecified behavior
j = i + i++; // unspecified behavior
j = i++ + ++i; // unspecified behavior

Also, since it inevitably will come up:
http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.15
 
A

Alf P. Steinbach

* andrew browning:
does i++ have the same potential for side effects as its pre-fix
equivilent ++i?

No, i++ is more side effect oriented than ++i because i++ has only one
reason for existence: producing a side effect in an expression.

i++ can be regarded as (temp = i, ++i, temp).

and if so, is it always dangerous to use them
No.


as in a for loop, or only in certain circumstances?

No. But prefer ++i. That way you tell the reader that you're not
interested in the side effect, and it can be more efficient.
 
A

andrew browning

got it.

am i too take it that i'm breaking usenet protocol somehow? i hope i
am not:(
 
A

Alf P. Steinbach

* andrew browning:
got it.

am i too take it that i'm breaking usenet protocol somehow? i hope i
am not:(

Well, now you are, because you forgot to quote what you responded to.
But originally you were not. Heh. :)
 

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,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top