Home > C Programming, Strange bugs > Choosing between a function and a macro definition

Choosing between a function and a macro definition

This is a common and a funny problem. So what is this all about? Let me put it like this…

We have a standard “c” function called _toupper and an equivalent macro is also available called _toupper. So my question is how to call function version of _toupper explicitly, if we write _toupper, macro version  get expanded inline, since preprocessor runs before compiler.

Here is the solution…

#include <ctype .h>

const char upper = _toupper( ch ); // Will invoke macro version
const char upper = (_toupper)(ch); // Will invoke function

Another routine is _fileno, implemented both as a function and as a macro. Apply same trick.

const int ErrFileNo = (_fileno)( stderr );
const int OutFileNo = _fileno( stdout );

Another option is to use #undef to undefine the macro definition.

#include </ctype><ctype .h>
#undef _toupper

A friend of mine was saying that he did encounter such bugs due to such “automagic” macro expansion.

Advertisements
  1. August 28, 2008 at 11:47 am

    🙂

  2. karlt
    August 28, 2008 at 11:43 am

    const char upper = (_toupper)(ch); // Will invoke function

    Ha! I like that! I think I’ve just found a new interview question!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: