again some incr/decrement question

R

rahul8143

hello,
why following both programs executes in different manner that
mean first goes in infinite loop and second one executes 0.
NOTE:- I am using Microsoft visual studio 6 to program C
programs.

1)
int funct2(int b)
{
if (b == 0)
return b;
else
funct1(b--);
}
int funct1(int a)
{
if (a == 0)
return a;
else
funct2(a--);
}
void main()
{
int a=7;
printf("%d",funct1(a));
}
2)
int funct2(int b)
{
if (b == 0)
return b;
else
funct1(--b);
}
int funct1(int a)
{
if (a == 0)
return a;
else
funct2(--a);
}
void main()
{
int a=7;
printf("%d",funct1(a));
}

regards,
rahul
 
D

Denis Kasak

hello,
why following both programs executes in different manner that
mean first goes in infinite loop and second one executes 0.
NOTE:- I am using Microsoft visual studio 6 to program C
programs.

1)
int funct2(int b)
{
if (b == 0)
return b;
else
funct1(b--);
}
int funct1(int a)
{
if (a == 0)
return a;
else
funct2(a--);
}
void main()

The main() function is defined as either int main(void) or int main(int
argc, char **argv).
{
int a=7;
printf("%d",funct1(a));
}

To answer your question - this program passes the argument 'a' to function
'funct1' which then compares it for equality with zero, which is false, and
then passes the value of 'a' to function 'funct2'. Since you used the
postdecrement operator, the value of 'a' does not get decreased prior to
parameter passing. Instead, it simply passes 7. The value that _does_ get
decreased is the value of the local variable 'a' in 'funct1' which
dissapears immediately after leaving it's scope (e.g. upon giving control to
'funct2'). So the two functions basically exchange the value 7 over and over
again.
2)
int funct2(int b)
{
if (b == 0)
return b;
else
funct1(--b);
}
int funct1(int a)
{
if (a == 0)
return a;
else
funct2(--a);
}
void main()
{
int a=7;
printf("%d",funct1(a));
}

The reason why this program prints 0 is that you used the predecrement
operator so the value of 'a' gets decreased *before* passing it to the other
function. The two functions continuosly decrease the value and pass it
around until it becomes 0 and the expression (a == 0) becomes true, thus
making the function return 'a' (which is 0 at that point).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top