Search code examples
cwhile-loopreturn

Return an expression inside a while loop - C language


I know that calling a return; from a while exits from the loop, but what happens if you call return VALUE inside a loop? And firstly, is it possible?

EDIT: Strangely - but not so much because now I have the expected behaviour - reorganizing the function to show the code now the "return" all work as they should do. Sorry for the silly question; I post the code anyway hoping it will be useful for someone with my same doubt.

#include <stdio.h>
int function();

int main(){
printf("MAIN BEFORE FUNCTION\n");

    function();
    printf("MAIN AFTER FUNCTION\n");

    getch();
    return 0;
}

int function(){
    printf("FUNCTION ENTERED\n");
    int i = 1;
    if (i < 3){
        printf("IF ENTERED\n");
        return;
        printf("IF AFTER RETURN\n");

    }
    printf("FUNCTION AFTER IF\n");

    while (i < 3){
        printf("WHILE ENTERED\n");
        return;
        printf("WHILE AFTER RETURN\n");


    }
    printf("FUNCTION END\n");

    //return from function
    return 0;


}

Solution

  • The return statement will exit the current function, not just the loop it is in.

    Whether you call return with or without a value depends on whether or not the function in question has a void return type.