when we use return keyword in c language

0 votes
asked Jul 26 by Sans (120 points)

2 Answers

0 votes
answered Jul 26 by LiOS (3,880 points)

There are many uses of the return keyword in C, but here are some of the main uses:

1 - return at end of script

  • Depending on the main used i.e. int main(), you should implement a return "value" at the end of the script. This may signify the success of the script executing to the computer and user.
  • Return codes are between 0 and 255 in Linux, with 0 resembling success at most basic terms
  • Fact in Linux, $? is a variable used by the kernel to the store the success of execution of a command/script.
  • It is not required to include a return if the main used is void
Example:

#include <stdio.h>

int main()
{
        printf("hello");

    return 0;
}

2 - return inside a function

  • Return value(s) back to a variable within the scope of the main script or another function
  • A void function doesn't have a return

#include <stdio.h>

int add(int a, int b){
    return a + b;
}

int main()
{
    printf("%d", add(4, 4));

    return 0;
}

3 - return anywhere inside the script

  • Similar to the main and return at end of script, we can use return "value" anywhere in the code. This can be passed back to the computer where the code will stop execution or be used by the code in a try catch etc.
  • Note, return 252 is the equivalent to return -4
Example:

#include <stdio.h>

int main()
{
    int a = 6;
    
    if(a == 6){
        return -4;
    }
    else
    {
        printf("hello");
    }

    return 0;
}

0 votes
answered Jul 27 by Peter Minarik (4,550 points)

Please, read the documentation of return.

TL;DR; When you want to terminate the execution of the current function and return the result of a (non-void) function.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...