How does Return work?!

Hey guys. How is it going? I just have a simple question, how do I know when and how to return something? I just don’t under stand the whole return thing in general… Thanks. : P

Good day,

Your question lacks some information. What do you mean by return something?

I assume you are talking about the return keyword.
If it is the case, return ends the current function (and the code after it is ignored) . You need to return something of the same type of your function.

exemple with a boolean

bool YourClass::IsGreaterThan(int a, int b)
{
  if ( a > b)
  {
    return true;
  }

 return false;
}

Of course, if you function is a void, you only need return; . There is nothing to return.

So could that end with “return true;” and false aswell?

No, NEVER

As soon as your code reaches a return, it quits the current function and the lines below are not executed. That is why in my exemple an else was not requiered.

An important note: if your function is not a void function, your code always has to return something (same type of your function). If it does not, a compile error will occur.

Oh ok. Do you think you could give me an example of it being used? your first example is kinda hard to understand.

I’m not sure why that example needed to be in a class but here’s an example using that.

bool IsGreaterThan(int a, int b)
{
    if ( a > b)
    {
        return true;
    }
    return false;
}

int main()
{
    bool bIsGreater = IsGreater(5,3); //true
    return 0;
}

Another example using a function made in the course

std::string GetGuess()
{
    std::string Line;
    std::getline(std::cin, Line);
    return Line;
}
int main()
{
    std::string Guess = GetGuess();
    return 0;
}

How does that last one work?

In exactly the same manner, the function is called and Line's value is returned at the end of the function. That returned value is then used to initialise Guess.

Wow. I just read it again…Now i think I understand it Lol. Thanks.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms