-5

The following code is to calculate (base^pow)%mod

Can any one explain to me the following code which involves in declaring a variable to a function i want to know the value the function assigns to the variable and how it does it.

int tmp = mypow( base, pow >> 1, mod );

The whole code:

#include<stdio.h>

int mypow( int base, int pow, int mod )
{
    if( pow == 0 ) return 1;
    if( pow % 2 == 0 ){
        int tmp = mypow( base, pow >> 1, mod );
    printf("\n\n%d\n\n",tmp);
        return tmp * tmp % mod;
    }
    else{
        return base * mypow( base, pow - 1, mod ) % mod;
    }
}

int main(){
    printf("\n\n%d\n\n", mypow(25,20,22));
    return 0;
}
timrau
  • 22,578
  • 4
  • 51
  • 64
Shashank K
  • 388
  • 4
  • 13
  • 1
    It's a normal variable declaration with initialization. It's not different from e.g. `int tmp = 5;`, except that the initialization expression is a function call. – Some programmer dude Mar 07 '14 at 06:30
  • It's an implementation of the recursive algorithm described [here](http://en.wikipedia.org/wiki/Exponentiation_by_squaring#Basic_method). – Brett Hale Mar 07 '14 at 06:31

3 Answers3

2

The function will be executed with the given parameters, then it will return() the processed value. This value will then be assigned to the var.

int tmp = mypow( base, pow >> 1, mod );

This line is part of the recursive implementation of the function.

1
int tmp = mypow( base, pow >> 1, mod );

This defines a variable named tmp, and initializes it to the value returned by function call mypow( base, pow >> 1, mod ).

Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
0

It isn't called variable declaration to a function perhaps arguments passed to function.

So when you try calling a function as mypow(25,20,22), these three actual args are passed to callee as formal arguments. In C you always do call by reference method in passing the args.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46