Pregunta

Considere el siguiente fragmento de código C:

char sum_char(char a,char b)
{
   char c = a+b;
   return c;
}

Implica -

  1. Convierta el segundo parámetro en extensión de signo.
  2. Inserte el parámetro de extensión firmado en la pila como b.
  3. Convierta el primer parámetro en extensión de signo.
  4. Inserte el parámetro de extensión firmado en la pila como.
  5. Agregue a y b, convierta el resultado en char y guárdelo en c.
  6. C es nuevamente el signo extendido.
  7. El signo c extendido se copia al registro de valor de retorno y la función regresa a la persona que llama.
  8. Para almacenar el resultado de la función de llamada nuevamente, convierta int a char.

Mis preguntas son -

  1. ¿Quién hace esto?
  2. ¿Cuál es la necesidad de hacer tantas conversiones?
  3. ¿Reducirá/aumentará el rendimiento de la máquina/compilador?
  4. Si está reduciendo el rendimiento, ¿qué debemos hacer para aumentarlo?
¿Fue útil?

Solución

  1. ¿Quién hace esto? - En última instancia, es la CPU quien hace esto;el compilador genera todas las instrucciones relevantes para que la CPU realice las conversiones
  2. ¿Cuál es la necesidad de hacer tantas conversiones? - Las conversiones son necesarias para garantizar la coherencia de los resultados en múltiples plataformas compatibles con múltiples compiladores de C.
  3. ¿Reducirá/aumentará el rendimiento de la máquina/compilador? - Esto reducirá el rendimiento en comparación con "no hacer nada", pero nadie notará la diferencia.
  4. Si está reduciendo el rendimiento, ¿qué debemos hacer para aumentarlo? - Nada:si debes realizar operaciones aritméticas en chars, entonces realizas operaciones aritméticas en chars.Deje que el optimizador se encargue de eliminar todas las instrucciones innecesarias para su plataforma.En la mayoría de los casos, la CPU tiene instrucciones que son compatibles con la semántica requerida por el lenguaje C, por lo que el código generado será muy corto.

Por supuesto, si no necesita realizar operaciones con caracteres firmados, puede realizar operaciones con caracteres sin firmar.Esto eliminó una gran cantidad de extensión de señales.

Otros consejos

Las conversiones que usted describe solo se realizan en la máquina abstracta.Un compilador puede atajo todo esto si conduce al mismo comportamiento observable.

Al cambiar las optimizaciones, mi compilador se traduce en el siguiente ensamblador

sum_char:
.LFB0:
    .cfi_startproc
    leal    (%rsi,%rdi), %eax
    ret
    .cfi_endproc
.LFE0:
    .size   sum_char, .-sum_char

que es solo una adición (oculta en la instrucción leal) y un salto de ret.

  1. The code, when run. The compiler generates the needed code to implement the specified semantics for the programming language.
  2. I'm not sure in the pushing to "stack" you're talking about, there's no such requirement in C as far as I know.
  3. That doesn't make sense; compared to what?
  4. You can try removing the pointless c variable, and just have return (char) (a + b);. That said, I don't think there's much to be "optimized" in this function. It should compile to very little code. If you can get it inlined, it will probably be on the order of 1 instruction.

I'm unsure as to the detail of your question. You refer repeatedly to sign-extension without citing any source; I guess you're assuming that the char data type will be extended to match the bit-ness of the CPU, but I don't think there's any guarantee that this is not the case already.

However, as a stab at answering your vague questions:

  1. The compiler does this in reponse to you writing the code. Who writes the code? A developer, I would imagine. You did this, when you wrote the question.
  2. If there is a necessity (for you don't cite your source), I imagine it is so that the CPU can handle the arithmetic natively.
  3. Technically it would reduce it, but only compared to a theoretical machine that has arbitrary bit-ness. Realistically, it makes no noticeable difference.
  4. There is a very slight performance gain if you use data types that match the native bit-ness of your architecture. However, this is very slight, and is usually not worth the inconvenience.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top