C return Statement Tutorial

In this section, we will learn what the return statement is and how to use it in C.

Note: we’re assuming you’re already familiar with the C functions.

return Statement in C

We mentioned in the `function` section that the keyword `return` is used when we want to return a value from a function that actually expected to return a value.

If that function doesn’t expect to return a value (the return type of the function is declared `void`) then there’s no need to use the `return` keyword.

Also, you should know that the `return` keyword can appear within the `for-loop`, `if-else` statement, `while-loop`, `do-while` loop, `switch-statement`.

But it cannot appear as the value assigned to a variable like:

`int i = return 3;` //WRONG…

Also, the moment the CPU reaches to the `return` statement, no-matter where this keyword is in the body of a function, it terminates that function and any instructions after this statement will be skipped. (A few compilers even throw warning if you put code after the `return` statement).

Note: before checking the example below, you might want to check the `if-else` statement section first if you don’t know what this statement does.

C return Statement Declaration

return value;

The value we put on the right side of the return keyword is the value that will be returned to the caller function. Note that the data type of this value must match the data type of the target function! For example, if the data type of the return value of a function is set to int, then we need to set a value of type int on the right side of the return keyword.

Example: using multiple return statement in C

include <stdio.h>

int main() {

    int inValue ;
    scanf("%d",&inValue);
    if (inValue> 100){
        return 0;
        printf("The value is larger than 100");
    }else{
        return 0;
        printf("The value is less than 100");
    }
    return 0;
}

If you compile and run the example above, no-matter what integer value you enter to this program, you won’t see any message on the screen.

This is because within the body of `if` and `else` statements, the first instruction is to run the `return` statement and that will terminate the function `main` (no-matter how many instructions appears below this statement, those instructions will be ignored).

That’s why the call to `printf` functions in these two statements is simply ignored.

More to Read:

C void Function

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies