Page 116 - C-Language
P. 116

#define is used in this way so as to avoid having to explicitly write out some constant value in
              many different places in a source code file. This is important in case you need to change the
              constant value later on; it's much less bug-prone to change it once, in the #define, than to
              have to change it in multiple places scattered all over the code.


              Because #define just does advanced search and replace, you can also declare macros. For
              instance:


               #define ISTRUE(stm) do{stm = stm ? 1 : 0;}while(0)
               // in the function:
               a = x;
               ISTRUE(a);


              becomes:


               // in the function:
               a = x;
               do {
                   a = a ? 1 : 0;
               } while(0);


              At first approximation, this effect is roughly the same as with inline functions, but the
              preprocessor doesn't provide type checking for #define macros. This is well known to be
              error-prone and their use necessitates great caution.


              Also note here, that the preprocessor would also replace comments with a blanks as
              explained below.

            2.  Includes:


              #include is used to access function definitions defined outside of a source code file. For
              instance:


                #include <stdio.h>


              causes the preprocessor to paste the contents of <stdio.h> into the source code file at the
              location of the #include statement before it gets compiled. #include is almost always used to
              include header files, which are files which mainly contain function declarations and #define
              statements. In this case, we use #include in order to be able to use functions such as printf
              and scanf, whose declarations are located in the file stdio.h. C compilers do not allow you to
              use a function unless it has previously been declared or defined in that file; #include
              statements are thus the way to re-use previously-written code in your C programs.

            3.  Logic operations:


               #if defined A || defined B
               variable = another_variable + 1;
               #else
               variable = another_variable * 2;
               #endif




        https://riptutorial.com/                                                                               92
   111   112   113   114   115   116   117   118   119   120   121