What does ## mean for the C(C++) preprocessor?
Asked Answered
B

4

15

I have a C program below:

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

when I run just the preprocessor it expands this as

{
int var12=100;
printf("%d",var12);
}

which is the reason why the output is 100.

Can anybody tell me how/why the preprocessor expands var##12 to var12?

Ballot answered 8/1, 2010 at 6:17 Comment(3)
Because that's what ## means in the C preprocessor. It's like saying "why does i++ increment i?". Because the C standard says so!Maribeth
@Richo....its not a home work.as i am not much familiar with the preprocessor i had this question in my mind.it might be easy for for you and might look like a homework.but for those who does'nt know this is not so easy to understand.Ballot
I'm sure this is must be duplicate, but of course both google and SO search fail when it comes to searching for ##Hardan
H
35

nothing too fancy: ## tells the preprocessor to concatenate the left and right sides

see http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation

Hypesthesia answered 8/1, 2010 at 6:19 Comment(0)
B
6

because ## is a token concatenation operator for the c preprocessor.

Or maybe I don't understand the question.

Bailiff answered 8/1, 2010 at 6:19 Comment(1)
It concatenates tokens, not strings.Bubal
S
6

## is Token Pasting Operator

The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token and therefore cannot be the first or last token in the macro definition.

If a formal parameter in a macro definition is preceded or followed by the token-pasting operator, the formal parameter is immediately replaced by the unexpanded actual argument. Macro expansion is not performed on the argument prior to replacement.

Spindly answered 8/1, 2010 at 6:21 Comment(0)
I
2

#define f(g,g2) g##g2

## is usued to concatenate two macros in c-preprocessor. So before compiling f(var,12) should replace by the preprocessor with var12 and hence you got the output.

Inaptitude answered 8/1, 2010 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.