Jump to content
  • Advertisement
Sign in to follow this  
Afr0m@n

## concatenating macro directive

This topic is 4449 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!