BOOL or BOOLEAN - is that the question?

    Somehow I never thought that it is better to use BOOL or BOOLEAN? Of course, BOOL is shorter and BOOL is found in all Windows tutorials. No matter how! Just yesterday, I spent an hour searching for an error where it should not have been.

    It turned out that the only true type directly related to the bool type, which is defined by the C ++ language standards, is BOOLEAN. And BOOL is nothing more than “typedef int BOOL;” and is located in windows.h (more precisely, in WinDef.h, but it doesn’t matter)

    Let’s take a closer look at the source code of the function comparing two numbers:
    #include<stdio.h>#include<windows.h>boolCompareInt(int i1, int i2){
        if (i1==i2)
            returntrue; //UPD1: было TRUEelsereturnfalse; //UPD1: было FALSE
    }
    typedefBOOL(*CallBack)(int, int);
    voidmain(void){
        CallBack IsEqual = (CallBack)CompareInt;
        if ( !IsEqual(0x1234, 0x5678) )
            printf("Not equals");
        elseprintf("Equals");
    }
    After compiling Visual Studio and starting it, we have: Equals

    Then change BOOL to BOOLEAN:
    typedef BOOLEAN (*CallBack)(int, int);
    Compile, run, get: Not equals (which should have been right from the start)

    Conclusion: never use BOOL, only BOOLEAN.

    UPD1: Corrected in the return function, it was TRUE / FALSE became true / false for the purity of the experiment.

    UPD2: Revealing "black magic." Returning bool is in char type (CPU al register), since bool in Visual Studio is equal to char (and BOOLEAN is also equated to char there, so replacing BOOL with BOOLEAN removes the error).

    But the BOOL type is equal to int (eax register), therefore, when the function returns false (it's FALSE), then only the low byte al is set to zero, and the high bytes (ah and other eax) - there will be non-zero garbage, to which BOOL, which incorporates the result of bool, will react like eax! = 0 and an error will occur.

    We would have to go to the branch with eax == 0 (Not equals) inside the last if, and switched to the branch with eax! = 0 (Equals), because the CompareInt function returned to us only al equal to 0, and the oldest (garbage) bytes in eax, the CompareInt function was not set to 0. (by mistake?)

    UPD3: By the way, Borland Builder C ++ compiled this code with the ancient (2006), all eax bits when false are returned inside the CompareInt function are explicitly set to 0 by xor eax , eax - therefore there is no error.

    Also popular now: