Search code examples
c++functionreturn-type

C++ return value type (integer) does not match the function type


#include <iostream>
#include <ctime>
using namespace std;


void randNum()
{
    int num1 = (rand() % 12) + 1;
    int num2 = (rand() % 12) + 1;
    int answer;
    answer = num1 * num2;

    return answer, num1, num2;
}
int main()
{
    srand(time(NULL));
}

I get the error return value type does not match the function type. Answer is an integer but it won't return regardless.


Solution

  • You can't return 3 things. You may wrap it in a struct if you wish. And make your function return the struct instead of void. In main, call your function

    #include <iostream>
    #include <ctime>
    using namespace std;
    
    
    struct three_values {
        int a;
        int b;
        int c;
    };
    
    three_values randNum()
    {
        three_values return_me;
        int num1 = (rand() % 12) + 1;
        int num2 = (rand() % 12) + 1;
        int answer;
        answer = num1 * num2;
        return_me.a = num1;
        return_me.b = num2;
        return_me.c = answer;
        return return_me;
    }
    
    int main()
    {
        srand(time(NULL));
        three_values var = randNum();
    
        std::cout << "num_1 = " << var.a << ", " << "num_2 = " << var.b << std::endl;
        std::cout << var.a << "*" << var.b << " = " << var.c << std::endl;
    }
    

    Possible output:

    num_1 = 6, num_2 = 7                                                         
    6*7 = 42