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;
}