Returning Data from Functions in C: A Beginner’s Guide

Master returning data from C functions with this beginner’s guide. Learn about return statements, function prototypes, and best practices with practical examples. Perfect for new C programmers building foundational skills.
code
c
Author

Steven P. Sanderson II, MPH

Published

April 30, 2025

Keywords

Programming, C functions, returning data from functions, C programming functions, function return values, C function return types, function prototypes in C, void functions, return statement in C, function parameters, C programming basics, how to return values from C functions, returning multiple values in C functions, common mistakes in C function returns, C function return value best practices, beginner’s guide to C function returns

Author’s Note: I’m learning as I write this series, so I might make mistakes or present concepts in ways that could be improved. This article represents my current understanding, and I welcome feedback to enhance future content.

Introduction

Returning data from functions is a fundamental concept in C programming that every beginner needs to master. In this comprehensive guide, we’ll explore how C functions return values, the best practices to follow, and common pitfalls to avoid. By the end, you’ll have a solid understanding of this core programming concept.

Functions in C can return only one value to the calling function. This limitation requires careful planning when designing your code, but with proper techniques, you can effectively work within this constraint and create clean, efficient programs.


Understanding Return Values in C

The Basics of Function Returns

In C, the return statement serves a crucial purpose: it sends a value back to the calling function and terminates the execution of the current function. For example:

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

When this function executes, it calculates the sum and then returns that value to wherever the function was called from.

Return Data Types

Before you can return a value, you must declare what type of value your function will return:

  • Explicit return type: Specified before the function name (e.g., int, float, char)
  • Default return type: If not specified, C assumes int by default
  • No return value: Use void when the function doesn’t return anything

For example:

int getCount() { /* Returns an integer */ }
float calculateAverage() { /* Returns a floating-point number */ }
void displayMessage() { /* Returns nothing */ }

Key Takeaway: Always explicitly declare your function’s return type to avoid unexpected behavior. Relying on the default int type can lead to subtle bugs.


Function Prototypes

Function prototypes are declarations that tell the compiler about a function’s name, return type, and parameters before the function is actually defined. They should be placed before the main() function:

float gradeAverage(float test1, float test2, float test3);

int main() {
    float average = gradeAverage(85.0, 90.5, 78.5);
    printf("Your average grade is: %.2f\n", average);
    return 0;
}

float gradeAverage(float test1, float test2, float test3) {
    return (test1 + test2 + test3) / 3;
}

Why Prototypes Matter

Prototypes are essential because they:

  1. Help the compiler verify that functions are called correctly
  2. Ensure proper data type conversion for arguments
  3. Allow you to define functions after they’re called
  4. Make your code more readable and organized

Without a proper prototype, especially for non-integer return types, your program might behave unexpectedly.


Best Practices for Returning Data

1. Always Use Function Prototypes

Except for main() (if it’s the first function in your file), always prototype your functions to avoid issues with non-int return types.

2. Do Something with the Returned Value

It’s generally poor practice to ignore return values:

// Good practice
int result = calculateSum(5, 10);
printf("The sum is: %d\n", result);

// Poor practice (ignoring the return value)
calculateSum(5, 10);

3. Return Expressions Directly

You can make your code more concise by returning expressions directly:

// Instead of this:
float calculateTotal(int quantity, float price) {
    float total = quantity * price;
    return total;
}

// Do this:
float calculateTotal(int quantity, float price) {
    return (quantity * price);
}

4. Match Parameter Lists

Ensure that parameter lists in prototypes, calling, and receiving functions all match in number, order, and type.

5. Include Appropriate Header Files

Many built-in C functions have prototypes in standard header files. Always include the appropriate headers to access these functions:

#include <stdio.h>   // For printf(), scanf(), etc.
#include <math.h>    // For sqrt(), pow(), etc.
#include <string.h>  // For strlen(), strcmp(), etc.

Complete Examples

Example 1: Basic Function Returning an Integer

#include <stdio.h>

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

int main() {
    int result = add(5, 3);
    printf("The sum is %d\n", result);
    return 0;
}

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

Example 2: Function Returning a Float

#include <stdio.h>

// Function prototype
float average(float num1, float num2, float num3);

int main() {
    float avg = average(4.0, 6.0, 8.0);
    printf("The average is %.2f\n", avg);
    return 0;
}

// Function definition
float average(float num1, float num2, float num3) {
    return (num1 + num2 + num3) / 3;
}

Example 3: Void Function (No Return Value)

#include <stdio.h>

// Function prototype
void printMessage();

int main() {
    printMessage();
    return 0;
}

// Function definition
void printMessage() {
    printf("Hello, World!\n");
    // No return statement needed (though return; is valid)
}

Your Turn! A Hands-on Exercise

Let’s practice by creating a temperature conversion function. Write a function that converts Celsius to Fahrenheit using the formula: F = C × 9/5 + 32

See Solution
#include <stdio.h>

// Function prototype
float celsiusToFahrenheit(float celsius);

int main() {
    float tempC = 25.0;
    float tempF = celsiusToFahrenheit(tempC);
    
    printf("%.1f degrees Celsius is equal to %.1f degrees Fahrenheit\n", tempC, tempF);
    return 0;
}

// Function definition
float celsiusToFahrenheit(float celsius) {
    return (celsius * 9.0/5.0) + 32.0;
}
This program defines a function that takes a temperature in Celsius and returns its equivalent in Fahrenheit. Notice the proper prototype definition and how we store and use the returned value.

Common Mistakes and Pitfalls

1. Trying to Return Multiple Values Directly

C functions can only return one value. If you need to return multiple values, you have alternatives:

  • Use pointers as parameters to modify variables
  • Return a structure containing multiple values
  • Use global variables (though this is generally not recommended)

2. Forgetting to Specify the Return Type

When you don’t specify a return type, C assumes int by default, which can cause problems if you’re returning a different data type:

// Problematic: implicitly returns int
someFunction() {
    return 3.14;  // Will truncate to 3
}

// Correct: explicitly returns float
float someFunction() {
    return 3.14;  // Returns 3.14
}

3. Missing Prototypes for Non-int Return Types

Without proper prototypes, C assumes functions return int, leading to data corruption for other return types:

#include <stdio.h>

// Missing prototype for function returning float

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

float divideNumbers(int a, int b) {
    return (float)a / b;
}

4. Expecting Functions to Change Argument Values

Functions operate on copies of the values passed to them, not the original variables (unless pointers are used):

void tryToModify(int x) {
    x = 100;  // Only modifies the local copy
}

int main() {
    int number = 5;
    tryToModify(number);
    printf("%d\n", number);  // Still prints 5, not 100
    return 0;
}

5. Not Using the Returned Value

Ignoring return values can lead to logical errors and missed opportunities for error handling:

// Poor practice: ignoring the result
sqrt(16);  // Calculation happens but result is discarded

// Good practice: using the result
double root = sqrt(16);
printf("The square root is %.1f\n", root);

Key Takeaways

  • C functions can return only one value to the calling function
  • Always specify the return data type before the function name
  • Use function prototypes placed before main() to avoid issues
  • The void keyword indicates that a function doesn’t return anything
  • You can return expressions directly: return (a + b);
  • If you need to return multiple values, use pointers, structures, or arrays

Conclusion

Understanding how to properly return data from functions is crucial for writing effective C programs. By following the best practices outlined in this article—using proper return types, creating function prototypes, and avoiding common pitfalls—you’ll be well on your way to writing cleaner, more efficient C code.

As you continue your C programming journey, practice these concepts regularly to reinforce your understanding. Remember that mastering the fundamentals will make learning more advanced topics much easier.


FAQs About Returning Data from Functions in C

1. Can a C function return an array directly?

No, C functions cannot return arrays directly. Instead, you can return a pointer to an array, return a structure containing an array, or modify an array passed as a parameter.

2. What happens if I don’t include a return statement in a non-void function?

If you don’t include a return statement in a non-void function, the behavior is undefined. The function may return a garbage value, which could cause unexpected behavior in your program.

3. Can I return a value from a void function?

No, a void function cannot return a value. If you need to return a value, you should change the function’s return type accordingly.

4. What’s the difference between “return” and “return 0”?

“return” alone just exits the function without returning a value (valid only in void functions). “return 0” exits the function and returns the integer value 0 to the calling function.

5. How can I return multiple values from a function?

While C functions can only return one value directly, you can: use pointers as parameters, return a structure containing multiple values, or use global variables (though this is generally not recommended).


References

  1. The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie
  2. C Standard Library Reference
  3. GNU C Library Documentation
  4. Microsoft C Runtime Library Reference
  5. C Programming Wikibook

Did you find this tutorial helpful? Share it with fellow beginner C programmers who might benefit from understanding function return values! If you have any questions or suggestions for future topics in this series, let me know in the comments.


Happy Coding! 🚀

Return Data from Functions in C

You can connect with me at any one of the below:

Telegram Channel here: https://t.me/steveondata

LinkedIn Network here: https://www.linkedin.com/in/spsanderson/

Mastadon Social here: https://mstdn.social/@stevensanderson

RStats Network here: https://rstats.me/@spsanderson

GitHub Network here: https://github.com/spsanderson

Bluesky Network here: https://bsky.app/profile/spsanderson.com

My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ

You.com Referral Link: https://you.com/join/EHSLDTL6