Page 109 - C-Language
P. 109

function that is non-recursive but that sets up the seed values for the recursive calculation.
            2.  Check to see whether the current value(s) being processed match the base case. If so,
              process and return the value.
            3.  Redefine the answer in terms of a smaller or simpler sub-problem or sub-problems.
            4.  Run the algorithm on the sub-problem.
            5.  Combine the results in the formulation of the answer.
            6.  Return the results.


        Source: Recursive Function


        Checking logical expression against 'true'


        The original C standard had no intrinsic Boolean type, so bool, true and false had no inherent
        meaning and were often defined by programmers. Typically true would be defined as 1 and false
        would be defined as 0.

        C99


        C99 adds the built-in type _Bool and the header <stdbool.h> which defines bool (expanding to _Bool
        ), false and true. It also allows you to redefine bool, true and false, but notes that this is an
        obsolescent feature.

        More importantly, logical expressions treat anything that evaluates to zero as false and any non-
        zero evaluation as true. For example:


         /* Return 'true' if the most significant bit is set */
         bool isUpperBitSet(uint8_t bitField)
         {
             if ((bitField & 0x80) == true)  /* Comparison only succeeds if true is 0x80 and bitField
         has that bit set */
             {
                 return true;
             }
             else
             {
                 return false;
             }
         }


        In the above example, the function is trying to check if the upper bit is set and return true if it is.
        However, by explicitly checking against true, the if statement will only succeed if (bitfield &
        0x80) evaluates to whatever true is defined as, which is typically 1 and very seldom 0x80. Either
        explicitly check against the case you expect:


         /* Return 'true' if the most significant bit is set */
         bool isUpperBitSet(uint8_t bitField)
         {
             if ((bitField & 0x80) == 0x80) /* Explicitly test for the case we expect */
             {
                 return true;
             }
             else



        https://riptutorial.com/                                                                               85
   104   105   106   107   108   109   110   111   112   113   114