# Thread: Factrorial using conditonal operator in a macro?

1. ## Factrorial using conditonal operator in a macro?

Can I find the factorial of a number using conditional operator in a macro definition?

#define fact(n) ( n == 0 ? 1 ; (n*(fact(n-1) ) ) )

since recursive definition is not allowed in macros, is there any work around?

Thanks,
Anoop. 2. You can solve the problem by removing the recursion and using a while-loop or such instead.

Shiro 3. As far as I now, the ?: operator is C++ not C. Correct me if wrong.
Second, it is not:
Code:
`#define fact(n) ( n == 0 ? 1 ; (n*(fact(n-1) ) ) )`
But:
Code:
`#define fact(n) ( n == 0 ? 1 :(n*(fact(n-1) ) ) )` 4. first off, ? exists in C, second off, changing that still doesn't make that macro make sense...

Essentially, macros are a shortcut for replacing certain types of things in the code when you compile it. for example, if I type this into my code:
#define MAX 30
when I compile my code, every instance of MAX will be replaced by 30...
I think if he defines n to a number before that recursive macro, it MIGHT be compilable, but his program's size may increase exponentally relative the the value of n.... 5. Okie that ";" obviously was a typo. Sorry for that.

As tzuchan has pointed out, it exists in C.

Now, defining N might not work since the compiler would look for
#define TOKEN VALUE
and would complain if the VALUE is expressed in terms of TOKEN again. Moreover, if you define N, you dont need to put a conditional operator.

What I wanted to know was if someone has cheated the compiler and calculated the factorial using the conditional operator in a macro.

Generalizing, has anyone, used recursive MACRO?

Thanks,
Anoop. 6. >Generalizing, has anyone, used recursive MACRO?
You can't. It simply replaces the text. Take this code for example:
Code:
```#define for if( 0 ); else for

int main( void )
{

int i;
for( i = 0; i < 5; ++i )
putc( '0' + i );

return 0;

}```
This is what it might look like after the macros are dealt with:
Code:
```int main( void )
{

int i;
if( 0 ); else for( i = 0; i < 5; ++i )
putc( '0' + i );

return 0;

}```
All it does is replaces every instance of 'for' in the code with 'if( 0 ); else for'. No recursion. Can't do it. 7. You can use a macro for calculating the factorial of n like this:

Code:
```#define FAC(n) \
for (f = 1, i = 2; i <= n; i++) \
{ \
f *= i; \
}```
Note that if you use such a macro, then in the function where you use it, the variables, n, f and i must have been declared before the macro can be used. A macro can't be recursive, since a macro isn't a call to something. As XSquared said, it is a replacement of some text. Popular pages Recent additions 