tags:

views:

165

answers:

5
#define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}

The above program prints 100 in c by concatenating var and 12. How does g##g2 work??

+8  A: 

## just pastes tokens together. It is a preprocessor directive.

E.g.

#define PASTE(a,b)  a##b

int i=PASTE(1,2);  /* int i=12; */
jldupont
A: 

## is the preprocessor "command" for concatenating what comes before and after.

Jim Buck
A: 

So after preprocess it will look like this:

main()
{
int var12=100;
printf("%d",var12);
}
dimba
A: 

This is token pasting, described here for gcc. Token pasting is done by the preprocessor, not the compiler.

bluebrother
A: 

Concatenation is being performed by the preprocessor because you used the ## command.

When you are unsure what the preprocessor is doing you can ask gcc to stop after it has run the preprocessor. Since this is before the compiler runs, the output is fairly easy to understand.

For example, assume you have a file pre.c

#define FOO 123
#define CONCAT(x,y) x##y
#define STRING(x) #x

void main()
{
    int a = FOO;
    int b = CONCAT(123,4567);
    char* c = STRING(IGetQuoted);
}

You can produce the preprocessor output by passing the -E option to gcc.

$ gcc -E pre.c 
# 1 "pre.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "pre.c"




void main()
{
    int a = 123;
    int b = 1234567;
    char* c = "IGetQuoted";
}

Keep in mind that #include will pull in the contents of the file it specifies and can make the preprocessor output rather long.

Tim Kryger
-1 (not really) for `void main()`!
pmg