macro?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • parinaz
    New Member
    • Jan 2010
    • 5

    macro?

    what is macro in C programming language?and what does it do?can some body
    explain it to me in simple terms?
    Thank you!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    A macro is a way to refer to something indirectly. For example, suppose your program deals with the color red and that red has a value of 2. Next suppose you have hard-coded those 2's in about 500 places in your program and then your boos changes the specs so that red is now zero. How you have to go through the code change all the 2's to zero and not accidentally chnage a 2 to zero that should remain a 2 becuse it refers to something else.

    A macro works around this problem. Here is a macro:

    Code:
    #define RED  2
    The pre-processor runs before your compiler and it looks for lines starting with a #. These are preprocessor directives and the #define is a macro. The preprocessor will go through the program and change all occurrences of RED to 2. The compiler sees the 2.

    Now when you boss changes red to zero all you need do is:

    Code:
    #define RED 0
    and rebuild yout program.

    You can use macros to represent blocks of code also.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      It may be helpful to think of the programming process as consisting of a sequence of steps:
      • edit-time (when you use an editor to write the source code)
      • compile-time (when the tool-chain compiles source code into object code)
      • link-time (when the tool-chain links object code into executable code)
      • execution-time (when the program actually executes)

      (This is only a partial list of the steps.)

      Some editors allow you to mechanize part of the editing process (through macros, regular expression substitution, cut and paste, etc.). These mechanizations can be interpreted as small standalone programs that execute during edit-time to alter/create the C source code.

      C macros can similarly be thought of as small standalone programs that execute during compile-time to alter/create the C source code. Actually, the macros execute (or "expand") during preprocess-time which is just prior to compile-time, but that distinction can be deferred.

      Finally, your program does its thing during execution-time.

      By the way, each step can produce error messages. It is much easier to interpret the error message when you take into account which step generated it.

      Comment

      Working...