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

302
Visualizações
Is this expression statement in a C programming exam question undefined behavior?

In a C programming exam question, I found this:

int a, b=0, x=4, y=5;
a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);

Is this expression UB?

I would say no, because of the sequence point (SP) between logic operators and between expressions of ?:. So, to my understanding, the horrible hack would be evaluated correctly as:

      x%y                             this gives 4 (exp is true)
    a=    b+1                         this assigns 1 to a and we have a SP (exp is true)
              y--                     this is not evaluated
                     x-=y             this assigns -1 to x and we have a SP (exp is true) 
                              y-=6    this is not evaluated
a=                                    this assigns the result of the || operator to a (1)

Finally a=1, x=-1, nothing else is changed. Any mistake?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Is this expression statement in a C programming exam question undefined behavior?

Is this expression UB?

No.

Any mistake?

No.

I wanted to write some text here, but you have already written the explanation... Nothing for me to do. Notes: There is also a sequence point after ?. Even if y-- would be evaluated, because && is a sequence point, it still would be fine.

over 4 years ago · Santiago Trujillo Relatório

0

#include <stdio.h>

int main() {
    int a, b=0, x=4, y=5;
    a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);
    printf("a=%i\nb=%i\nx=%i\ny=%i\n", a,b,x,y);
    return 0;
}

OUTPUT:

a=1
b=0
x=-1
y=5

So I think you are right about everything but I do not think it counts as undefined behavior.

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