I read this output question from a site
#include<iostream>
#include<conio.h>
#define f(g,g2) g##g2
using namespace std;
int main()
{
int var12=100;
cout<<f(var,12);
getch();
return 0;
}
Answer is 100 ie. value of var12.But can anyone explain me how?
This is a discussion on Output question#define f(g,g2) g##g2 within the C++ Programming forums, part of the General Programming Boards category; I read this output question from a site #include<iostream> #include<conio.h> #define f(g,g2) g##g2 using namespace std; int main() { int ...
I read this output question from a site
#include<iostream>
#include<conio.h>
#define f(g,g2) g##g2
using namespace std;
int main()
{
int var12=100;
cout<<f(var,12);
getch();
return 0;
}
Answer is 100 ie. value of var12.But can anyone explain me how?
## pastes or merges two tokens into one. So f(var, 12) is replaced by the tokens "var" and "12" (both tokens without the quotes) pasted together (i.e. as the token var12).
In your example, if you try to print f(var,13) you will get a complaint from the compiler about there being no variable named var13.
Thanks grumpy
But why this is illegal
Code:int gr8; cout<<gr##8;
Because you're not using a macro.
## is a preprocessor directive, which is only used within #define'd macros.
The logic is that there are a number of (logical) phases in the process of compiling from source code to file object file (or executable). One of the early phases is the preprocessor which, among other things, does text substitution (eg replacing an #include directive with he contents of the #include'd file, replacing macros with whatever those macros expand to). A subsequent phase of compilation is actually turning the preprocessed source into (typically) machine specific object code.
So, to simplify your example somewhat .... This ....
will be converted by the preprocessor to something that looks like this;Code:#include <iostream> #define f(g,g2) g##g2 using namespace std; int main() { int var12=100; cout << f(var,12) << endl; return 0; }
and this preprocessed code is fed through the compilation phase which turns the preprocessed code into an object file (or something similar, depending on your compiler).Code:// preprocessed contents of <iostream> here verbatim using namespace std; int main() { int var12=100; cout << var12 << endl; return 0; }
If the preprocessor sees ## outside the context of a macro, it does nothing to it. So the compilation phase would see "cout << gr##8;" exactly as is. And the compiler phase knows nothing about preprocessor directives, so complains when it sees this code.