Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
How does `int sum = n + - + - + - + n` compile where `n` is an `int`?

This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked.

The code is:

#include <stdio.h>

int main()
{
    int n=2;
    int sum = n + - + - + - + n;  /* This line */
    printf("%d\n", sum);
    return 0;
}

And the output is:

0

I am completely confused how the code compiled and what is happening behind the scene.

How does the line int sum = n + - + - + - + n; work?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

All but the first are just unary operators.

n + - + - + - + n

is equivalent to

n + (-(+(-(+(-(+n))))))

which is in turn simply equal to

n + (-n)

after resolving all the unary operators.

-n is, of course, ordinary negation; +n does essentially nothing (though it has the side effect of forcing integral promotion).

over 4 years ago · Santiago Trujillo Denunciar

0

int sum = n + - + - + - + n;
/*          b u u u u u u   */
/* Order:   7 6 5 4 3 2 1   */

is equivalent to:

n + (-(+(-(+(-(+n))))));

or simply n + (-n)

Note that unary operators bind more tightly than binary operators in C opeartor precedance table and associativity of unary operator +- is from right to left while of binary +- operators in from left to right.

over 4 years ago · Santiago Trujillo Denunciar

0

Both of + and - are also unary operators. The result of +n is the (promoted) value of n. The result of -n is the negative of (promoted) n.

n + - + - + - + n;

is equivalent to:

n + (-(+(-(+(-(+n))))))

which is basically n + (-n) assuming no overflow happens.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda