Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

582
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda