[Solved] Functions returning random values in C++. Can’t find issue


Your messagereturn() and greet() functions are declared as returning bool values, but neither one of them actually returns anything, so the values are random. Since you are sending the return values to std::cout, but the functions send their own messages to std::cout directly, they should not be returning any bool values at all.

Also, since gradecalculate() is only called for ages 5-17, there is no need for it to check the age again. It is not good to write a function that has no return value under certain conditions.

Try this:

#include <iostream>

using namespace std;

int gradecalculate (int age)
{
    return age-5;
}

void messagereturn (int age)
{
    if (age < 5)
    {cout << "You are too young for school." << endl;}

    else if (age > 17)
    {cout << "You are too old for school." << endl;}

    else
    {cout << "You should be in grade " << gradecalculate (age) << endl;}
}

void greet (int age)
{
    if (age == 17)
    {cout << "Hello Senior!" << endl;}
}

int main ()
{
    int age;
    cout << "Enter your age: ";
    cin >> age;

    messagereturn (age);
    greet (age);

    return 0;
}

Alternatively, you could merge the functions together and have it return a std::string that you then send to std::cout:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int gradecalculate (int age)
{
    return age-5;
}

string messagereturn (int age)
{
    if (age < 5)
    {return "You are too young for school.";}

    else if (age > 17)
    {return "You are too old for school.";}

    else
    {
        ostringstream oss;
        oss << "You should be in grade " << gradecalculate(age);
        if (age == 17)
        {oss << "\n" << "Hello Senior!";}
        return oss.str();
    }
}

int main ()
{
    int age;
    cout << "Enter your age: ";
    cin >> age;

    cout << messagereturn (age) << endl;

    return 0;
}

solved Functions returning random values in C++. Can’t find issue