πŸ” C Function Return Values

In C, a function can return a value back to the caller using the return statement. The return type is specified before the function name in the declaration and definition.

πŸ”Ή What is a Return Value?

A return value is the output a function sends back after it completes. This allows the calling code to use that result in further operations.

πŸ“ Example 1: Function Returning an Integer

This function adds two numbers and returns the result.

#include <stdio.h>

int add(int a, int b); // Function declaration

int main() {
    int sum = add(4, 6); // Store the return value
    printf("Sum: %d\n", sum);
    return 0;
}

int add(int a, int b) {
    return a + b; // Return the result
}
  

Try It Now

πŸ“ Example 2: Returning a Float

This function divides two numbers and returns a floating-point result.

#include <stdio.h>

float divide(int x, int y); // Function declaration

int main() {
    float result = divide(10, 3);
    printf("Result: %.2f\n", result);
    return 0;
}

float divide(int x, int y) {
    return (float)x / y; // Typecast to float
}
  

Try It Now

πŸ“ Example 3: Function Returning Nothing (void)

If a function doesn’t need to return anything, use void as its return type.

#include <stdio.h>

void greet(); // Declaration

int main() {
    greet(); // Just call, no return value
    return 0;
}

void greet() {
    printf("Hello, World!\n");
}
  

Try It Now

🎯 Summary

  • Use return to send values back from a function.
  • Return type must match the value being returned.
  • void functions don’t return anything.
  • Returned values can be stored in variables or used directly in expressions.

πŸ’‘ Try It Yourself

Change the return type, return different data, or try chaining function calls. Return values make your functions truly powerful and reusable!