Recentemente ho affrontato uno strano comportamento utilizzando l'operatore di spostamento a destra.Comportamento strano dell'operatore di spostamento a destra (1 >> 32)
Il seguente programma:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdint.h>
int foo(int a, int b)
{
return a >> b;
}
int bar(uint64_t a, int b)
{
return a >> b;
}
int main(int argc, char** argv)
{
std::cout << "foo(1, 32): " << foo(1, 32) << std::endl;
std::cout << "bar(1, 32): " << bar(1, 32) << std::endl;
std::cout << "1 >> 32: " << (1 >> 32) << std::endl; //warning here
std::cout << "(int)1 >> (int)32: " << ((int)1 >> (int)32) << std::endl; //warning here
return EXIT_SUCCESS;
}
Uscite:
foo(1, 32): 1 // Should be 0 (but I guess I'm missing something)
bar(1, 32): 0
1 >> 32: 0
(int)1 >> (int)32: 0
Cosa accade con la funzione foo()
? Capisco che l'unica differenza tra ciò che fa e le ultime 2 righe, è che le ultime due righe vengono valutate in fase di compilazione. E perché funziona "se uso un intero a 64 bit?
Tutte le luci a riguardo saranno molto apprezzate!
Sicuramente correlata, qui è quello che dà g++
:
> g++ -o test test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:20:36: warning: right shift count >= width of type
test.cpp:21:56: warning: right shift count >= width of type
Mi chiedo solo, perché la "non una domanda vera" voto ravvicinato ?! – ereOn
domanda molto interessante .. anche se pensavo che ruotare di un numero elevato si tradurrebbe in 0. Non sapevo che fosse UB. – Naveen
odiatori che odieranno. :) È l'unica spiegazione per i downvotes drive-by. – tzaman