Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

579
Views
Why does "A = A + B - (B = A)" swap values in C?

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.”

over 4 years ago · Santiago Trujillo Report

0

You should not rely on code like that to work because it relies on the fact that it is processed from left to right.

Any implementation that does not do it like that is going to make it fail.

You should avoid writing code that does not work in all cases on all platforms and is not compiler independent, or relies on things that are not documented nor well defined.

So why does it work if you go from left to right : Suppose A = 1 and B = 3
A = A + B - ( B = A);
A = 1 + 3 - (1) = 3
The assignment of B happens where i left the () Bottom line is that only when processing left to right , the assignment of B to A is happening later.

When processing right to left same example : A = A + B - ( B = A);
A = 1 + 1 - (1) = 1
Now the assignment of B is happening first.

Again, you should not rely on code that is not clear for the reader what is happening, and which is compiler dependent which this is the case here.

over 4 years ago · Santiago Trujillo Report

0

This is only "shorter" than the standard/obvious way to do it, in the number of lines/semicolons used.

  • It introduces additional operations which might disallow optimization by the compiler
  • It worsens readability (as mentioned by D.R.)
  • It (ab)uses non-standard behavior (as mentioned by Marion), which might make it fail with some compilers

You should never use it.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!