Search code examples
cprogramming-languages

Consider a C variant, where comparison operators return all bits set for true values and 0 for false


I'm looking at a question and can't seem to see how it would deviate from normal C. In C, 1 represents true (of course any non-zero value is also considered true) and 0 represents false. In what scenarios would a C variant deviate from traditional C, if we instead returned all bits set when conditions evaluate to true. To me it seems the same, but I know there must be an aspect im not considering, or just not thinking of the question in the right way. Would really appreciate a hint in the right direction.


Solution

  • An advantage is that nominally branchless selections can be written more easily:

    // Select c or d based on comparison of a and b.
    static int Select(int a, int b, int c, int d)
    {
        int mask = a < b;
        return c & mask | d & ~mask;
    }
    

    In standard C, this can be written as return a < b ? c : d;, but that nominally involves testing a < b and then executing a branch instruction. Branch instructions often have deleterious effects on processor performance, and we seek to avoid them in high-performance code. So have a bit mask instead that can be used to make the selection using on logical instructions, not branches, could be beneficial in some circumstances.

    However, questions like this are hypothetical and dated. A compiler might optimize a < b ? c : d. Or, even if using a mask is better, there is a question of how the compiler is going to generate it to implement a < b—that might in itself involve performing a test and executing a branch instruction, thus negating the benefit. So questions like this generally do not have good answers in isolation. They serve only in a classroom context to prompt or portray student familiarity with the material.