6
#include <iostream>

using namespace std;

int main()
{
   cout << "sizeof(unsigned int): " << sizeof(unsigned int) << endl; 
   unsigned a = 1;
   int i = 0;
   while (a) {         
        cout << "a[" << i++ << "]: " << a << endl;        
        a <<= 1;
   }

   cout << "a[" << i << "]: " << a << endl;

   unsigned b = 1;
   unsigned c = (b << 31);
   unsigned d = (b << 32);

   cout << "c: " << c << endl;
   cout << "d: " << d << endl;

   return 0;
}

/* 出力http://www.compileonline.com/compile_cpp_online.php */

Compiling the source code....
$g++ main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
main.cpp: In function 'int main()':
main.cpp:19:23: warning: left shift count >= width of type [enabled by default]

Executing the program....
$demo

sizeof(unsigned int): 4
a[0]: 1
a[1]: 2
a[2]: 4
a[3]: 8
a[4]: 16
a[5]: 32
a[6]: 64
a[7]: 128
a[8]: 256
a[9]: 512
a[10]: 1024
a[11]: 2048
a[12]: 4096
a[13]: 8192
a[14]: 16384
a[15]: 32768
a[16]: 65536
a[17]: 131072
a[18]: 262144
a[19]: 524288
a[20]: 1048576
a[21]: 2097152
a[22]: 4194304
a[23]: 8388608
a[24]: 16777216
a[25]: 33554432
a[26]: 67108864
a[27]: 134217728
a[28]: 268435456
a[29]: 536870912
a[30]: 1073741824
a[31]: 2147483648
a[32]: 0
c: 2147483648
d: 1

質問> ご覧のとおり、はa[320です。d01

4

3 に答える 3

14

これは、C/C++ では未定義の動作です。

このようなシフトが発生した場合、異なる CPU は異なることを行うため、標準では特にこれを未定義のままにしています。具体的には、32 ビット Intel では、シフト量の下位 5 ビットのみが CPU によって使用され、残りのビットは単に無視されると思います。私の記憶が正しければ、PowerPC と 64 ビット Intel は両方とも下位 6 ビットを使用し、残りを無視します。

高水準言語は、結果をより論理的に一貫性のあるものに修正することでこれを滑らかにしようとするかもしれませんが、C/C++ のような低水準言語は「金属に近い」ように設計されており、単一のビット シフトを生成する必要があります。<<オペレーターへの指示。

于 2013-09-13T16:21:22.180 に答える