简体   繁体   中英

Recursive Function Error1

I am making a program that the user inputs integers and outputs them in reverse. It is a recursive function. The Problem now is that it outputs an infinite of 0's. Please tell me where is the error in my code. and I need some pointers. Please help.

#include <iostream>

using namespace std;

void printreverse(int);

int main()
{
    int x;
    cout << "Enter numbers: ";
    cin >> x;

    printreverse(x);

    return 0;
}
void printreverse(int x)
{
    if(x<10)
        cout << x;
    else
        cout << x%10;
        printreverse(x/10);
}

C++ is not Python. You need to surround your else block by braces, like so

else
{ // need brace here
    cout << x%10;
    printreverse(x/10);
} // and here

otherwise only the first statement after the else is being executed (and the final printreverse(x/10) will always be executed, even for 0 , so you end up overflowing the stack).

I recommend you to always put braces, even for a single statement in an if/else , precisely for reasons similar to the one you just bumped into.

You have wrong identing in printreverse . It should be like this:

void printreverse(int x)
{
    if(x<10)
        cout << x;
    else
        cout << x%10;

    printreverse(x/10);
}

First it prints x or x%10, then it recurses regardless of what x is. If you wanted more than one statement done in a consequent or alternative you need to use a block. Blocks are denoted with {} in C-decendants. They are so usual that some people actually think conditionals and control flow syntax need to have them. Anyway if the identing was the intended behaviour you should write it like:

void printreverse(int x)
{
    if(x<10) {
        cout << x;
    } else {
        cout << x%10;
        printreverse(x/10);
    }
}

Whenever I use braces on one term in an if I add them for every one even when it's not really needed. Some coding standards, like PSR2, require blocks always to remove the chance of ever getting bugs like this.

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