Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why we add return at the end of function

+7 votes
asked Apr 19, 2025 by syed musawir (190 points)

3 Answers

+1 vote
answered Apr 25, 2025 by Razo Chahkoyan (160 points)
in python or other language?
+1 vote
answered Apr 26, 2025 by Peter Minarik (101,340 points)

I will use the C language to explain this, but the logic applies to most "modern" languages, not just C (so it applies to C#, Java, Python, you name it).

Let's consider the two functions below. They could be implemented in many ways, I'll just do one way for the sake of the argument about return.

int GetSalary()
{
    return 100000;
}

that will get you the salary of an employee, and

void PrintSalary(int salary)
{
    printf("The salary is %d.\n", salary);
    return;
}

that will print the salary on the standard output.

In GetSalary(), we use the return statement so we can specify what the function should tell the caller about the value of the salary. We specify the return value (int) to be 100,000. Without this, the function would not work.

In PrintSalary(), we may add a return statement at the end of the function to indicate we want to finish the function (or any time earlier, if we want to exit early, e.g. on a condition), but since this function does not return anything (void), the return statement is optional. PrintSalary() would work fine without one.

In other programming languages, such as good old Pascal, GetSalary() was called a function, because it returned a value, but PrintSalary() was called a procedure, because it did not return any value, just did some series of instructions without returning anything to the caller.

I hope this helps. ;)

0 votes
answered Apr 30, 2025 by LUCIANO BERTINI (140 points)
In order to return a value to the caller function.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...