Return values and void functions

Home / C Programming / Return values and void functions

Return values and void functions


In C programming, functions can have return values or be declared as void functions, depending on whether they are intended to return a value to the calling code or not.

1. Functions with Return Values:

Functions with return values are used when you want the function to compute some result and pass it back to the calling code. The return type of such functions is specified in the function prototype and definition.

The syntax for a function with a return value is as follows:

return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {

    // Function body

    // ...

    return value; // Return statement

}

Here's an example of a function that calculates the sum of two integers and returns the result:

#include <stdio.h>

int add(int num1, int num2) {

    int sum = num1 + num2;

    return sum;

}

int main() {

    int result = add(5, 7);

    printf("Sum: %d\n", result); // Output: Sum: 12

    return 0;

}


2. Void Functions:

Void functions, as the name suggests, do not return any value. They are useful when you want to perform certain tasks without needing to pass back a result.

The syntax for a void function is as follows:

void function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {

    // Function body

    // ...

    // No return statement needed

}

Here's an example of a void function that prints a message:

#include <stdio.h>

void printMessage() {

    printf("Hello, this is a void function!\n");

}

int main() {

    printMessage(); // Output: Hello, this is a void function!

    return 0;

}

It's important to note that if a function is declared to have a return type other than void, it must contain a return statement with a value of that return type. On the other hand, if a function is declared with a return type of void, it should not have any return statement or should have a return statement without any value.

Here's an example of a void function with a return statement (without a value):

#include <stdio.h>

void displayMessage() {

    printf("This is a void function with a return statement.\n");

    return; // This return statement is valid in a void function.

}

int main() {

    displayMessage(); // Output: This is a void function with a return statement.

    return 0;

}