The C Preprocessor :: Parameterized Macros

The C Preprocessor :: Parameterized Macros

  • One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number:
      int square(int x) {
    return x * x;
    }
    We can instead rewrite this using a macro:
      #define square(x) ((x) * (x))
    A few things you should notice. First square(x) The left parentheses must "cuddle" with the macro identifier. The next thing that should catch your eye are the parenthesis surrounding the x's. These are necessary... what if we used this macro as square(1 + 1)? Imagine if the macro didn't have those parentheses? It would become ( 1 + 1 * 1 + 1 ). Instead of our desired result of 4, we would get 3. Thus the added parentheses will make the expression ( (1 + 1) * (1 + 1) ). This is a fundamental difference between macros and functions. You don't have to worry about this with functions, but you must consider this when using macros.
  • Remeber that pass by value vs. pass by reference issue earlier? I said that you could go around this by using a macro. Here is swap in action when using a macro:
      #define swap(x, y) { int tmp = x; x = y; y = tmp }
    Now we have swapping code that works. Why does this work? It's because the CPP just simply replaces text. Wherever swap is called, the CPP will replace the macro call with the defined text. We'll go into how we can do this with pointers later.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post