C programming - Return Statement in Function
In C programming, the return
statement is used to exit a function and return a value to the calling statement. The return
statement can be used to return a value of any data type, including integers, floating-point numbers, characters, and even pointers.
The syntax for the return
statement in C is as follows:
return expression;
In this syntax, expression
is an optional value to be returned by the function. If the function returns no value, you can omit the expression.
Here's an example of a function that returns an integer value using the return
statement:
int add(int num1, int num2) { int sum = num1 + num2; return sum; }
In this example, the add
function takes two integer parameters num1
and num2
, performs an addition operation, and returns the sum of the two numbers using the return
statement.
When a function is called, the return
statement is used to return a value to the calling statement. For example, consider the following statement that calls the add
function:
int result = add(5, 7);
In this statement, the add
function is called with the arguments 5
and 7
, and the resulting sum is returned using the return
statement. The returned value is assigned to the variable result
, which can then be used in other parts of the program.