The difference between a function-like macro and a function in C, C++

I’ve been working my way through some of the open courseware computer science materials that MIT hosts. The past few nights, I’ve been reviewing the “Practical Programming in C” lecture notes and assignments. For the most part, the first few assignments were really easy for me – few new concepts.

One bit that tripped me up were what looked like functions, but were actually macros (I later learned these are called macro-like functions).

Now, I know C is an ancient language and I’m sure this has been discussed thousands of times (or more) – but I still think it warrants a blog post. So here is a macro-like function:

#define squaredM(x) x*x

And here is a function:

double squaredF(double x)
{
    return x*x;
}

Here is what looks like the same code calling functions that do the same things:
double ans = 18.0 / squaredM(2+1);
double ans = 18.0 / squaredF(2+1);

You might assume that both pieces of code would be handled the same way. And you’d be wrong. I did not assume that both pieces of code would be handled the same way, but I also made an incorrect assumption how a function-like macro worked (I did not already know). The key difference is that a function-like macro is pre-processed and then compiled, while the function is compiled. In plain english, that means that when you compile the program, the preprocessor essentially creates a new piece of code, with the macro substituted in, and then compiles:

double ans = 18.0 / 2+1*2+1;

Order of operations tells us that division / multiplication, left to right, should happen first. So you actually end up with 9 + 2 + 1.

In the second example, using a function, 2+1 is already a float of 3.0 when it is received by squaredF. This may not ever be useful to you, but I thought it was cool and wanted to share it.

References:
Wikipedia (C Preprocessor)
IBM AIX Compilers Reference
MIT Open Courseware Answers

This entry was posted in C Programming Language, C++. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted February 17, 2012 at 11:22 am | Permalink

    Nice post – definitely worth noting that since the macro is equivalent to a substitution, wrapping 2 + 1 in parenthesis fixes the discrepancy. Great topic!

  2. Calvin Froedge
    Posted February 17, 2012 at 3:23 pm | Permalink

    Yo, thanks, John! Yea, you’re right. The MIT Open Courseware also compares several of the different possibilities based on parenthesis uses. Thanks for reading!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>