When I excuted this belo program, it is printing 5
inifnitely. Why? Is it because the decrement is not happening or before decrement happens function call is happening?
I have tried the alternate way making fun(--n)
, it gave me correct answer. But why it is not working for fun(n--)
?
void fun(int n)
{
if(!n)
{
cout << n << " " << endl;
}
else
{
cout << n << " "<<endl;
fun(n--);
}
}
int main()
{
int n = 5;
fun(n);
system("pause");
return 0;
}
you need to do foo(--n)
and not foo(n--)
so when you do foo(n--)
you decement the value of n, but send to the foo
function the n bofore decrementing. as you can guess that will go forever
void fun(int n)
{
if(!n)
{
cout << n << " " << endl;
}
else
{
cout << n << " "<<endl;
fun(--n);
}
}
int main()
{
int n = 5;
fun(n);
system("pause");
return 0;
}
to learn more on the difference between n--
and --n
read here
Because fun(n--);
means call fun
with value n
and then decrement n
.
Because n--
returns n
before decrementing its value. Since you are calling your function that way, n
always comes with the same value. You could write func(n--)
that way :
int temp = n;
n = n - 1;
func(temp);
Note that foo( n-- )
will return n
and then decrement n
by one (see this ), hence returning 5, 5, 5, ... repeated. You need to do one of the following:
foo( --n ); // or,
foo( n - 1 );
... and thus your code should look like this:
void fun( int n ) {
if( !n ) {
cout << n << " " << endl;
} else {
cout << n << " "<< endl;
n--;
fun( n );
}
}
int main( void ) {
int n = 5;
fun( n );
system("pause");
return 0;
}
Aside: It's good practice to not include any increment or decrement operations within another expression. Had you of done the following it would of been ok:
n--;
foo( n );
... it can lead to confusion as a client (and even as the programmer) if you begin incrementing and decrementing within expressions. Consider this as another example where doing so is a bad idea:
if ( ( condition_1 == true ) && ( i++ == val ) )
... if the first condition is false
it will never reach the second condition and hence not increment i
.
Use fun(--n)
instead of fun(n--)
The reason this happens this way is because n--
decrements after the function has been run returning 5 repeatedly while --n
decrements before.
try :
void fun(int n)
{
if(!n)
{
cout << n << " " << endl;
}
else
{
cout << n << " "<<endl;
fun(--n);
}
}
您为fun()提供的值与上一次调用中提供的值相同。
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.