Localicé un error extremadamente desagradable que se escondía detrás de esta pequeña joya. Soy consciente de que según la especificación de C ++, los desbordamientos firmados son un comportamiento indefinido, pero solo cuando el desbordamiento se produce cuando el valor se extiende al ancho de bits sizeof(int)
. Según tengo entendido, aumentar un char
nunca debería ser un comportamiento indefinido siempre que sizeof(char) < sizeof(int)
. Pero eso no explica cómo c
se obtiene un valor imposible . Como un entero de 8 bits, ¿cómo pueden c
contener valores mayores que su ancho de bits?
Código
// Compiled with gcc-4.7.2
#include <cstdio>
#include <stdint.h>
#include <climits>
int main()
{
int8_t c = 0;
printf("SCHAR_MIN: %i\n", SCHAR_MIN);
printf("SCHAR_MAX: %i\n", SCHAR_MAX);
for (int32_t i = 0; i <= 300; i++)
printf("c: %i\n", c--);
printf("c: %i\n", c);
return 0;
}
Salida
SCHAR_MIN: -128
SCHAR_MAX: 127
c: 0
c: -1
c: -2
c: -3
...
c: -127
c: -128 // <= The next value should still be an 8-bit value.
c: -129 // <= What? That's more than 8 bits!
c: -130 // <= Uh...
c: -131
...
c: -297
c: -298 // <= Getting ridiculous now.
c: -299
c: -300
c: -45 // <= ..........
Compruébalo en ideone.
printf()
funciona la conversión?