Returning values from functions.

Lesson 3.3: Returning Values from Functions


In this lesson, you'll learn how to make your functions more useful by having them return results back to the calling code. This allows functions to perform calculations, retrieve information, or make decisions that can be used in other parts of your program.


Why Return Values?


Communication: Returning values allows functions to communicate information back to the code that called them.

Modularity: Functions that return values can be used as building blocks in larger expressions or calculations.

Versatility: Functions that return values can be used in different contexts, making your code more flexible and reusable.

The return Statement


The return statement is used to:


Exit a function immediately.

Send a value back to the code that called the function.

Syntax:


C

return value;


Example:

C

#include <stdio.h>


int square(int num) {

    int result = num * num;

    return result;

}


int main() {

    int number = 5;

    int squared = square(number);  // Call the function and store the returned value


    printf("The square of %d is %d\n", number, squared);  // Output: The square of 5 is 25

    return 0;

}


Choosing a Return Type


The return type of a function specifies the type of data it sends back.

Common return types include:

int: For returning integer values.

double: For returning floating-point values.

char: For returning character values.

void: For functions that don't return anything.

Returning Multiple Values (Indirectly)


C functions can only return a single value directly. However, you can work around this limitation using pointers or structures.


Using Pointers: You can pass pointers to variables as arguments to a function, allowing the function to modify the values stored at those memory addresses.

Using Structures: You can create a struct to bundle multiple values together and return the struct as a single value.

Example: Returning Multiple Values Using Pointers


C

#include <stdio.h>


void getQuotientAndRemainder(int dividend, int divisor, int *quotient, int *remainder) {

    *quotient = dividend / divisor;

    *remainder = dividend % divisor;

}


int main() {

    int a = 17, b = 5;

    int q, r;


    getQuotientAndRemainder(a, b, &q, &r); // Pass addresses of q and r


    printf("Quotient: %d, Remainder: %d\n", q, r); 

    return 0;

}


Output:


Quotient: 3, Remainder: 2

Important Notes


Function Return Value: If a function is declared with a return type, it must always return a value of that type. If you have no value to return, simply use return;.

Multiple Returns: You can have multiple return statements within a function. The first one encountered will terminate the function and return the value.

Let me know if you'd like more examples or specific use cases for returning values from functions!


Course Syllabus