I want to know if we can have recursive macros in C/C++? If yes, please provide a sample example.
Second thing: why am I not able to execute the below code? What is the mistake I am doing? Is it because of recursive macros?
# define pr(n) ((n==1)? 1 : pr(n-1))
void main ()
{
int a=5;
cout<<"result: "<< pr(5) <<endl;
getch();
}
Your compiler probably provides an option to only pre-process, not actually compile. This is useful if you are trying to find a problem in a macro. For example using
g++ -E:As you can see, it is not recursive.
pr(x)is only replaced once during pre-processing. The important thing to remember is that all the pre-processor does is blindly replace one text string with another, it doesn’t actually evaluate expressions like(x == 1).The reason your code will not compile is that
pr(5 -1)was not replaced by the pre-processor, so it ends up in the source as a call to an undefined function.