C Programming: Preprocessor Directives in C -> define Macro section

All Preprocessor directives

Objective of this post: How to define Macro? single line, multiple lines? Where can we define it?

Syntax and  explaination: 
            Single line : https://www.techonthenet.com/c_language/constants/create_define.php
           
== 1. To define single and multiple lines Macro  from online source  ==
#include <stdio.h>
#define NUMNER_PER_LINE 10 
// To define single line


/* Below is to define multiple lines */
#define PRINT_A_to_B(A, B) \
   { \
     int a=A, b=B, counterNumber=1; \
     printf("\nFrom=%d to %d have shown as below\n",a,b); \
     for( ; a<=b ; printf("%03d ",a) && a++ && counterNumber++) \
     { \
         if(0==counterNumber%NUMNER_PER_LINE) \
         { \
           printf("%03d\n",a); a++; counterNumber=1; \
         } \
     }; \
     printf("\n\n"); \
   };

int main(int argc, char *argv[])

    system("mode con: cols=150 lines=50"); /* To  set  size of console output */
    printf("1.  Compiler will replace Macro to source code first then compile text or source code to binary\n");
    printf("2.  We can define Macro anywhere including in function\n");
    printf("3.  Actually, we define Macro in one line. If it is too long you can type to the next line with \\ as above sample\n\n\n");
   
     PRINT_A_to_B(1, 23);
     PRINT_A_to_B(12, 35);
  
   return 0;
}

Above sample for define single and multiple Macro 
== 2. My experience about to define Macro everywhere ==

#include <stdio.h> int iPrintMaxNumber(int a, int b)
{
     #define MAX_NUMBER(x,y) (x > y ? x : y) /* define Macro in function */
     return MAX_NUMBER(a,b);
}

#define MIN_NUMBER(c,d) (c < d ? c : d) /* define Macro anywhere but NOT below main() */
int
main(int argc, char *argv[])

{
     system("mode con: cols=150 lines=50"); /* To set size of console output */
     printf("This sample to show you how to define Macro in function\n");
     printf("Max number between 10 and 23 = %d\n",iPrintMaxNumber(10, 23));
     printf("Max number between 23 and 23 = %d\n",iPrintMaxNumber(23, 23));
     printf("Max number between -5 and -100 = %d\n",iPrintMaxNumber(-5, -100));

     printf("\n\n\nThis sample to show you how to define Macro anywhere but before main() function\n");
     printf("MIN number between 10 and 23 = %d\n",MIN_NUMBER(10, 23));
     printf("MIN number between 23 and 23 = %d\n",MIN_NUMBER(23, 23));
     printf("MIN number between -5 and -100 = %d\n",MIN_NUMBER(-5, -100));


    return 0;

}
REMARK: Please take a look at comment. It tells you clearly.
This one shows how to define Macro everywhere


You may leave comment to improve it.
Thank you so much from THAILAND



















Popular posts from this blog

C Programming: How to improve C to support more Array N dimensions

C Programming: Superb E-Book from beginner to expert [C career semi retired]

C Programming: Understand For loop syntax in deep detail