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');


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?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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