Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "A = A + B - (B = A)" swap values in C? [duplicate]

Tags:

c

swap

To swap to integers, A and B, this seems to work in C,

A = A + B - ( B = A);

Why does this work? And if this works in all conditions, can this be used to shorten any other commonly implemented algorithms?

like image 915
n00b Avatar asked Aug 01 '15 06:08

n00b


1 Answers

Actually it invokes undefined behaviour according to standards-

C99 §6.5: “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.”

like image 185
ameyCU Avatar answered Oct 01 '22 10:10

ameyCU