C documentation V1 Help

Returning Data from Functions

In C programming, functions can return data to the calling code using the return statement. This allows functions to provide results or computed values for further use. Let's explore how to return data from functions in C.

Basic Return Statement

A function's return statement is used to send a value back to the calling code. Here's a simple example:

#include <stdio.h> // Function definition with a return value int square(int num) { return num * num; } int main() { // Function call and using the returned value int result = square(4); printf("Square: %d\n", result); return 0; }

In this example, the square function calculates the square of a number and returns the result. The main function calls square(4), and the returned value (16) is assigned to the result variable.

Returning Multiple Values

C functions can return only one value directly. However, you can use pointers to return multiple values indirectly. Example:

#include <stdio.h> // Function definition with multiple return values using pointers void calculate(int a, int b, int *sum, int *product) { *sum = a + b; *product = a * b; } int main() { int resultSum, resultProduct; // Function call and using the returned values via pointers calculate(5, 3, &resultSum, &resultProduct); printf("Sum: %d\n", resultSum); printf("Product: %d\n", resultProduct); return 0; }

In this example, the calculate function takes two numbers and calculates both their sum and product. The results are returned using pointers.

Returning Strings

Functions in C can also return strings, which are represented as arrays of characters. Example:

#include <stdio.h> // Function definition returning a string const char* greet() { return "Hello, world!"; } int main() { // Function call and using the returned string const char *greeting = greet(); printf("%s\n", greeting); return 0; }

In this example, the greet function returns a string, and the main function prints the returned string.

Understanding how to return data from functions is crucial for building modular and reusable code in C programming.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024