Page 69 - C-Language
P. 69

Chapter 8: Boolean




        Remarks



        To use the predefined type _Bool and the header <stdbool.h>, you must be using the C99/C11
        versions of C.

        To avoid compiler warnings and possibly errors, you should only use the typedef/define example if
        you're using C89 and previous versions of the language.



        Examples


        Using stdbool.h


        C99


        Using the system header file stdbool.h allows you to use bool as a Boolean data type. true
        evaluates to 1 and false evaluates to 0.


         #include <stdio.h>
         #include <stdbool.h>

         int main(void) {
             bool x = true;  /* equivalent to bool x = 1; */
             bool y = false; /* equivalent to bool y = 0; */
             if (x)  /* Functionally equivalent to if (x != 0) or if (x != false) */
             {
                 puts("This will print!");
             }
             if (!y) /* Functionally equivalent to if (y == 0) or if (y == false) */
             {
                 puts("This will also print!");
             }
         }


        bool is just a nice spelling for the data type _Bool. It has special rules when numbers or pointers
        are converted to it.

        Using #define



        C of all versions, will effectively treat any integer value other than 0 as true for comparison
        operators and the integer value 0 as false. If you don't have _Bool or bool as of C99 available, you
        could simulate a Boolean data type in C using #define macros, and you might still find such things
        in legacy code.



         #include <stdio.h>

         #define bool int
         #define true 1



        https://riptutorial.com/                                                                               45
   64   65   66   67   68   69   70   71   72   73   74