prefix increment operator and side-effects

S

subramanian100in

Stroustrup in his book "The C++ Programming Language - Third Edition
(NOT the special third edition)", mentions the following in page 125
in section "6.2.5 Increment and Decrement".
"By definition, ++lvalue means lvalue += 1, which again means lvalue =
lvalue + 1 provided lvalue has no side-effects".

Here I am unable to understand why Stroustrup has mentioned "provided
lvalue has no side-effects". Isn't the expression ++lvalue the same as
lvalue = lvalue + 1 always ? Kindly clarify with an example.

Thanks
V.Subramanian
 
N

Niels Dekker - no reply address

V.Subramanian said:
Stroustrup in his book "The C++ Programming Language - Third Edition
(NOT the special third edition)", mentions the following in page 125
in section "6.2.5 Increment and Decrement".
"By definition, ++lvalue means lvalue += 1, which again means lvalue =
lvalue + 1 provided lvalue has no side-effects".

Here I am unable to understand why Stroustrup has mentioned "provided
lvalue has no side-effects".

For example, suppose you have an object v, of a type similar to
std::vector<int>. You would expect ++v[0] to be equivalent to v[0] = v[0] +
1. But clearly that assumes that doing v[0] doesn't have some side-effect,
like doing std::cout << "Hey, operator[] is called".

Does that answer your question?
 
J

James Kanze

Stroustrup in his book "The C++ Programming Language - Third
Edition (NOT the special third edition)", mentions the
following in page 125 in section "6.2.5 Increment and
Decrement". "By definition, ++lvalue means lvalue += 1, which
again means lvalue = lvalue + 1 provided lvalue has no
side-effects".
Here I am unable to understand why Stroustrup has mentioned
"provided lvalue has no side-effects". Isn't the expression
++lvalue the same as lvalue = lvalue + 1 always ? Kindly
clarify with an example.

int* p;
++(*p ++); // which is NOT the same as:
*p ++ = *p ++ + 1; // undefined behavior...
 

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,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top