Why macros are created?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anchal Laller
    New Member
    • Jan 2011
    • 5

    #1

    Why macros are created?

    why macros are created, means these are not efficient, and its not good to use them , so why they are created and in what circumstances we should use these??
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    macros can be used for defining constants that may be used many times in a program, e.g. here I define the clock frequency and baudrates for the PIC24
    Code:
    // External oscillator frequency (we'll use the value in IrDA_dep.h)
    //#define SYSCLK  16000000UL
    #define SYSCLK  32000000UL		// 8MHz clock with FNOSC_PRIPLL (baud rate max is 115200)
    //#define SYSCLK  8000000UL		// 8MHz clock with FNOSC_PRI (baud rate max 57600)
    
    // Define the baud rate constants
    #define PC_BAUDRATE     115200UL //57600UL
    #define GSM_BAUDRATE    115200UL //57600UL
    #define GPS_BAUDRATE     9600UL //57600UL
    #define BT_BAUDRATE     115200UL //57600UL
    if I want to change the clock frequency I can the value associated with SYSCLK - in the above example I can comment and uncomment depending on the hardware.
    This saves going thru a large program file by file changing constants like SYSCLK and possibility missing some.

    macros with paramters enable one to define function like operations which are eveluated before compile time. e.g.
    Code:
    // macro to generate port definitions such as PORTDbits.RD6
    #define PORT(port, bit) PORT##port##bits.R##port##bit
    // macro to generate tris definitions such as TRISAbits.TRISA4
    #define TRIS(port, bit) TRIS##port##bits.TRIS##port##bit

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      The preprocessor macro capability is as old as the C language itself. New features of the language (like inline functions and const variables) have provided new and better ways to accomplish some of the things that were formerly done by macros. There are still legitimate uses for macros.

      Why do you say "these are not efficient, and its not good to use them"?

      Comment

      Working...