I want to tell you about two oddities with which I had to face, programming numerical algorithms in C. So, the first unexpected behavior for some programmers.
Here is a little prog.
Examine it. Bitwise ~ inverts the status of each bit of the byte A , which originally recorded by the unit. The result should be obtained 11111110b , i.e. 254 . Shifting the byte by one bit to the right, must obtain 127 . However, the code that allows, for example, the compiler gcc , the console displays the number 255 ! At first I thought that the priority of the case - suddenly compiler priority operations "kosyachit"? That is, if the first is to shift, and then - inversion (and that, logically ...). So what's the deal?
After some deliberation I came up with another hypothesis that the inversion of bytes given by the way (well, or double word), and then shifted inverted word. That's where it turns 255 - high-order bits in the word zeros inverting them have one. Then, making a shift of one bit to the right, in its low byte of all bits will be unity. This confirms the following code.
Now we get the correct result. But finally saw this, disassemble ELF-file which gives gcc . Here is a fragment of the resulting assembly code.
First through a stack unit falls into the 32-bit register eax . Further, it is inverted, and then shifted. The result comes out from the low part of the register AX - register al . This justifies my hypothesis - the units that were necessary for the byte at offset double word in it were. As it turned out, this situation is called Integer Promotion and is described in Section 6.3.1.1 of the standardC99 . You can download it here www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf second unexpected behavior for some programmers associated with real numbers. Have the following code.
Compiling it gcc 4.1.1 , getting 1004 . Again, the question - where does the strange result? Even this
also do not make a right. Climb standard C89 , it turned out that he did not regulate on how to work with real numbers. After all, when there was expansion of SSE , compilers started counting in mixed case - How to calculate quickly: something on the FPU , something on the SSE . The new standard C99 appeared some certainty. The compiler should expose the macro valueFLT_EVAL_METHOD (header file float.h ) to 0 , 1 , 2 for the way he thinks. So, 0 - all considered as written; 1 - float actually considered to double and then convert back to float ; 2 - all considered in Long Double , converting in float or double at the end of the calculations, respectively. Now to make considered prog wrong, you need to collect it
Only after that I brought to the console by 1005 . It turned out that my version of the compiler gcc not support macroFLT_EVAL_METHOD . By the way, Double gcc gives code to output in 1004 . Only Intel C 9.0 did normal code with Double , but when I recorded
(Where a and b have type Double ). Without a cast and there gives code 1004 .
No comments:
Post a Comment