Skip to study material
← Question index

QUESTION 10 · Functions

Explain the return statement and return types in C functions.

5 marks

Answer in brief

The return statement finishes the current function call. For a non-void function, it can also send a result value to the caller.

Syntax

return expression;  /* value-returning function */
return;             /* void function */

Return type

The type written before the function name specifies its result type. In double half(int n), the function returns a double. The expression n / 2.0 uses floating-point arithmetic, so half(7) returns 3.5. Returning a value can involve conversion to the declared return type.

Execution

When return is reached, later statements on that path in the same call do not execute. A function can contain several return statements for different conditions, but a particular call completes through only one return path. The caller resumes after the call with the returned result when there is one.

Important rules

  1. Use return; in a void function, rather than returning an ordinary value.
  2. Ensure every needed path of a value-returning function supplies a valid result. Falling off its end and then using the missing value has undefined behaviour, with the special main rule discussed separately.
  3. In a hosted program, returning 0 from main reports successful completion. Reaching the closing brace of main also returns 0.
  4. Do not return a pointer to an ordinary automatic local object: that object no longer exists after the call ends.

Example purpose

The sample separates calculation from display. half performs the calculation; main decides the output format. This allows the result to be used in a later calculation without changing half.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
double half(int n)
{
    return n / 2.0;
}
int main(void)
{
    printf("Half = %.1f\n", half(7));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Half = 3.5

Related exam questions

Related questions in the function declarations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(h) · 1 marks

    Define function signature.

    Paper P05 · page 1
  • September 2023 · Q1(h) · 1 marks

    What is the signature of a function?

    Paper P06 · page 1

View this category in the exam question bank →