Post/Pre Increment/Decrement ---------------------> Boon or Curse!

 Ah, 

so, We love Increment/Decrement operators ( well most of us ), don't we??


Be Cautious while using INCREMENT/DECREMENT operators when:

1) While Giving ARGUMENTS to a RECURSIVE FUNCTION:

Let's take an example of a recursive factorial()

int fact(int n)
{
    if(n==1)
    return 1;
    return n*fact(n--);
}

The above function may look straightforward but, the above function will call itself infinitely.

Why?

We have used post decrement ( -- ) while passing value to fact(). Lets recall, how does POST DECREMENT work?
--> It first assigns the value then decrement occurs.

so, we actually passed  N  instead of ( N-1 ) in argument, thus resulting in infinite recursion. 

We can instead use PRE DECREMENT OPERATOR.

Note: NEVER USE POST DECREMENT/INCREMENT OPERATORS while passing values to a function.



2) Don't use POST/PRE INCREMENT OPERATORS at all, when the recursion is not tail recursion:


Consider the below two functions:

int calc1(int a,int b)
{
    if(a>b)
        return 0;
    if(a%2==1)
    {
        return a + calc1(++a,b);
    }
    else
        return calc1(++a,b);
}


int calc(int a,int b)
{
    if(a>b)
        return 0;
    if(a%2==1)
    {
        return a + calc(a+1,b);
    }
    else
        return calc(a+1,b);
}


Draw the RECURSION TREE for both...( both the above functions are supposed to calculate the sum of all odd numbers in the given range RECURSIVELY )

let's take the range [ 1,2]..
We know that in the range [1,2], the sum of all odd numbers =1 ,.....

for function calc 1 :

a=1 ,
                return  a + calc1( ++a,b)            
                :     Now, this makes value of a=2 , so, actually the statement turns to 
                        
                            return 2 + calc1(2,2)

                        which will ultimately be 2 .. crazy 

Now, lets perform the same operation in function calc()
                         return  a + calc( a+1,b)            
                :     Now, this makes value of a=2 , so, this time 
                        
                            return 1 + calc(2,2)

                        which will ultimately be 1.

Thus, Always be careful with these operators while dealing with them in functions, Don't use any type of pre-increment/decrement operators when recursion is not TAIL RECURSION.





                

Comments

Post a Comment

Popular posts from this blog

Why typedef is handy ?