The result of the CC ++ shift operator is unpredictable.

zhaozj2021-02-08  509

It used to see the C standard that the behavior when the shift operator (<<, >>) is not determined:

., Ory ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

I didn't study this problem at the time. A few days ago, I had a netizen to believe this, I found out that this is related to the INTEL CPU shift operation. Here is the letter of the netizen and my reply:

Hello! Operator << As an efficient operation in the bit operation, but I encountered a problem: I found a very unclear place in the VC environment, below.

#include void main () {unsigned Int i, j; i = 35; // Why is the following two left shift operation results different? J = 1 << i; // j is 8 j = 1 << 35; // j is 0}

I don't know where it is not understood.

The reason is this: i = 35; j = 1 << i; these two sentences will be compiled into the following machine instructions in the case where the VC is not optimized.

MOV DWORD PTR [I], 23HMOV EAX, 1MOV ECX, DWORD PTR [i] SHL Eax, Clmov DWORD PTR [J], EAX

In the SHL, EAX = 1, CL = 35. When the Intel CPU performs the SHL instruction, the CL and 31 will be AND operation to limit the number of left shifts less than or equal to 31. Since 35 & 31 = 3, such an instruction is equivalent to shifting 1 left 3 bits, the result is 8.

J = 1 << 35; a sentence is a constant operation, and the compiler will directly calculate the results of 1 << 35 even if it is not optimized. The VC compiler found 35 more than 31, it will set the result to 0 directly. The machine instructions generated by this line code are:

Mov DWORD PTR [J], 0

For the above two cases, if the optimization switch of the VC compiler is turned on (such as compiling into a release version), the compiler will set the result to 0.

Therefore, in the C / C language, the shift operation should not exceed the boundary, otherwise, the result is unpredictable.

Here are an explanation of the number of SHL instructions in the Intel document:

The destination operand can be a register or a memory location. The count operand can be an immediate value or register CL. The count is masked to 5 bits, which limits the count range to 0 to 31. A special opcode encoding is provided for a Count of 1.

转载请注明原文地址:https://www.9cbs.com/read-162.html

New Post(0)