Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This works just fine, however, the assignment was to write a recursive "function". I'm curious to see if this should count.

Any comments / suggestions/ stuff I should watch out for are appreciated.

#include <iostream>
#include <functional>
#include <cctype>
#include <cstdlib>

int main() {

    char go_again = 'Y';

    do {

        int lhs, rhs;
        std::cout << "Enter 2 integer values: ";
        std::cin >> lhs >> rhs;

        if (lhs < 0 || rhs < 0)
            std::cout << "Implicit converstion to positive integers.\n";

        std::function<int(int, int)> 
            gcd = [&](int lhs, int rhs) -> int { 
                return rhs == 0 ? std::abs(lhs) : gcd(rhs, lhs % rhs); 
        };

        std::cout << "gcd == " << gcd(lhs, rhs) << '\n';
        std::cout << "Go again? <Y/N> ";
        std::cin >> go_again;

    } while (std::toupper(go_again) == 'Y');

}
share|improve this question

1 Answer 1

Not that familiar with C++, but that certainly looks like recursion to me...

The variable gcd contains a function, which then calls itself. The very definition of recursion.

But I would ask what you gain by not making it a regular function?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.