Ceres111
Ceres111

Reputation: 49

Preprocessor directive with hash

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

This code gives output 100, but if the preprocessor is implemented, printf will be rewritten as:

printf("%d",var##12);

Then, how the output came?

Upvotes: 2

Views: 859

Answers (2)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Because f(var, 12) is replaced with var12, which is the name of the variable you declared and assigned in the line above. The preprocessor directive ## pastes together the two arguments.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

The double hash ## is a token pasting operator of the preprocessor. The printf will be re-written like this:

printf("%d",var12); // No double-hash

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.

Upvotes: 1

Related Questions