Sign in to follow this  
Afr0m@n

## concatenating macro directive

Recommended Posts

I'm reading a good article on macros, but I can't seem to understand the ## preprocessor macro directive. It's supposed to concatenate something, but I don't understand how, or what purpose it serves. Here's my current code:
#include <iostream>

#define concatenate(arg1, arg2) arg1 ## arg2

int main()
{
    int concatenate(fire, fly);
    concatenate(fire, fly) = 1;
    
    std::cout << concatenate(fire, fly) << std::endl;
    return 0;
}    

According to the article, the preprocessed code will look something like this:
main()
{
     int firefly ;
     firefly = 1;
     printf("%d \n",firefly );
}
I still can't understand what's going on though, or why! :S Help, please?

Share this post


Link to post
Share on other sites
The ## operator pastes a macro token onto another token, eg:
#define READ(size) Read##size

This macro expands as follows:

READ(Byte) => ReadByte
READ(Word) => ReadWord

etc

Share this post


Link to post
Share on other sites
Quote:
Original post by Afr0m@n
I still can't understand what's going on though, or why! :S Help, please?


as the article (and you) state, the ## derective combines two arguments into one.

that is, in your example, the ## derective combines fire and fly to make firefly.

the way preprocessor derectives work in general is that they take effect before compilation, so that and macro called in your code is replaced by the actual body of the macro before compile time.

hence, when concatenate(fire, fly) gets precompiled, that macro call is replaced with the concatination of the two words into firefly, hence,
concatenate(fire, fly) -> firefly

similarly, if you had the macro:
#define SAFEDEL(ptr) if(ptr) { delete ptr; ptr = NULL; }

and called it in this code:

void foo(void)
{
myClass* pClassInstance = new myClass;

SAFEDEL(pClassInstace)
}






it would get precompiled into:

void foo(void)
{
myClass* pClassInstance = new myClass;

if (pClassInstance) { delete pClassInstance; pClassInstance = NULL; }
}






as far as why ## may be usefull, the article you link to states: "This is useful in forming unique variable names within macros."

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this