简体   繁体   中英

Why this C program behaves abnormally when the function is called as an argument

I created a program to calculate the power of a number. Please look into the working code:

    #include <stdio.h>
    #include <stdlib.h>

    int power(int,int);

    int main()
    {
        int num,n;
        scanf("%d %d",&num,&n);
        printf("power of %d to %d\n",num,n);

        printf("%d",power(num,n));
        return 0;
    }

    int power(int num,int n)
    {
        int result=0;
        if(n==0)
            return 1;
        if(n==1)
            return num;
        if(n%2!=0)
        {
            result=num*power(num,n-1);
        }
        else if(n%2==0)
        {
            result=power(num,n/2)*power(num,n/2); 
//why this hangs when i replace this statement with power(power(num,n/2),2)
        }

        return result;
    }

This program works fine as long as I don't replace the last statement with the one mentioned in the comments.

Could you please let me know the reason behind this abnormal behaviour?

This program works fine as long as I don't replace the last statement with the one mentioned in the comments.

Could you please let me know the reason behind this abnormal behaviour?

This isn't abnormal behavior.

power(power(num,n/2),2)

Is a recursive call where the base case is never reached because n == 2 therefore the else if clause for n % 2 == 0 is always going to be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM