Code Review

  • Thread starter Vijay Kumar R Zanvar
  • Start date
V

Vijay Kumar R Zanvar

The following statement exchanges int a & b.

a = (a+b) - (b=a);

Is there any trade off here?

Thanks.
 
C

Chris Dollin

Vijay said:
The following statement exchanges int a & b.

a = (a+b) - (b=a);

Is there any trade off here?

Yes: you have traded away clarity and correctness.

Clarity: it's utterly opaque. Compare with

{ int temp = a; a = b; b = temp; }

Correctness: let the initial values of a, b be A, B.

evaluate b = a [A] a: A, b: A
evaluate a+b [2A]
subtract b (from b=a) [A]
assign to a a: A, b: A

Oops.

Did you not realise that the compiler is free to evaluate the operands
of -, +, and = in any order it finds convenient?

You might think this is ... unwise ... [I do], but that's the way it is.

[I think there's also a more technical point about "only accessing the
value of in order to determine the value to be stored", but I'm not
going to seek the details, and the order-of-evaluation argument is
immediately compelling granted the premise.]
 
V

Vijay Kumar R Zanvar

[..]
Did you not realise that the compiler is free to evaluate the operands
of -, +, and = in any order it finds convenient?

You are right. I didn't.
 
A

Alan Balmer

The following statement exchanges int a & b.

a = (a+b) - (b=a);

Is there any trade off here?

Thanks.
No, only a down side. It's not likely to work as stated. It's
implementation dependent and possible even context dependent in a
given implementation.
 
D

Dan Pop

In said:
No, only a down side. It's not likely to work as stated. It's
implementation dependent and possible even context dependent in a
given implementation.

It's straight undefined behaviour:

2 Between the previous and next sequence point an object shall
have its stored value modified at most once by the evaluation
of an expression. Furthermore, the prior value shall be read
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
only to determine the value to be stored.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Have a closer look at b.

Dan
 

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,099
Messages
2,570,626
Members
47,237
Latest member
David123

Latest Threads

Top