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…

[sourcecode language=’cpp’]#include

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

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

[sourcecode language=’cpp’]const int ErrFileNo = (_fileno)( stderr );
const int OutFileNo = _fileno( stdout );[/sourcecode]

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

[sourcecode language=’cpp’]#include
#undef _toupper[/sourcecode]

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

2 thoughts on “Choosing between a function and a macro definition

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

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

Appreciate your comments...