0
0
CHow-ToBeginner · 3 min read

How to Return Value from Function in C: Simple Guide

In C, you return a value from a function using the return statement followed by the value you want to send back. The function's return type must match the type of the value you return, for example, int for integers or float for decimal numbers.
📐

Syntax

The basic syntax to return a value from a function in C is:

  • return_type function_name(parameters) { - declares the function with a specific return type.
  • return value; - sends the value back to the caller.
  • } - ends the function.

The return statement ends the function and sends the specified value to where the function was called.

c
return_type function_name(parameters) {
    // code
    return value;
}
💻

Example

This example shows a function that adds two integers and returns the sum. The main function calls it and prints the result.

c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(5, 3);
    printf("Sum is %d\n", result);
    return 0;
}
Output
Sum is 8
⚠️

Common Pitfalls

Common mistakes when returning values in C include:

  • Not matching the function's declared return type with the returned value type.
  • Forgetting the return statement in a non-void function, which can cause undefined behavior.
  • Returning a pointer to a local variable, which becomes invalid after the function ends.

Always ensure the returned value is valid and the function's return type matches it.

c
/* Wrong: returning pointer to local variable */
char* wrong() {
    char str[] = "hello";
    return str; // str is local and will be invalid
}

/* Right: returning pointer to static or dynamically allocated memory */
char* right() {
    static char str[] = "hello";
    return str; // valid because static lasts beyond function
}
📊

Quick Reference

ConceptDescription
Function Return TypeMust match the type of value returned
Return StatementEnds function and sends value back
Void FunctionsUse void return type and no return value
Returning PointersAvoid returning pointers to local variables
Multiple ReturnsFunctions can have multiple return statements

Key Takeaways

Use the return statement to send a value back from a function.
The function's declared return type must match the type of the returned value.
Never return pointers to local variables as they become invalid after the function ends.
Void functions do not return a value and use void as the return type.
You can have multiple return statements to exit a function early.