Tuesday, January 21, 2025
HomeProgrammingReturn Statement in C

Return Statement in C

In C programming, the return statement is used to exit from a function and optionally return a value to the calling function. The behavior of the return statement varies depending on whether the function is a void function (which doesn’t return a value) or a non-void function (which returns a value).

Syntax of the return statement:
return expression;

Where:

  • expression is the value you want to return from the function. The type of the expression must match the return type declared for the function.
Types of functions and their return statements:
  1. Void Function: A function with the void return type does not return any value. The return statement is used simply to exit the function.
    void example() {
        printf("This is a void function.\n");
        return;  // Optional, as control will exit the function automatically at the end
    }
    
  2. Non-void Function (Returns a Value): A function that returns a value must include a return statement that provides a value matching the declared return type.
    int add(int a, int b) {
        return a + b;  // Return the sum of a and b
    }
    
    int main() {
        int result = add(5, 3);
        printf("The sum is %d\n", result);
        return 0;  // Return value to indicate successful program termination
    }
    
Key Points:
  • Returning from a Function: When the return statement is executed, control is transferred back to the point where the function was called.
  • Function Return Type: If the function is declared with a return type other than void, you must return a value of that type. If the function is void, no value is returned.
  • Exiting Early: The return statement can be used to exit from a function before reaching the end, which can be useful for error handling or early termination based on certain conditions.
See also  How can you retrieve an enum value from a string in Java?
Example with Condition:
int find_max(int a, int b) {
    if (a > b) {
        return a;  // Return a if it is greater than b
    } else {
        return b;  // Otherwise return b
    }
}

int main() {
    int max_value = find_max(10, 20);
    printf("The maximum value is %d\n", max_value);
    return 0;
}

This example demonstrates the use of the return statement based on a condition inside the function.

RELATED ARTICLES

Numpy.array() In Python

How to Run Node Server

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x