return type in Function
Table of Content:
Return Statement with respect to parameter or arguments in c, there may be four type of condition with respect to arguments, they are below-
- Take Nothing Return Nothing
- Take Nothing Return Something
- Take Something Return Nothing
- Take Something Return Something
Take Nothind Return Nothing
Program
#include void main( ) { sum() ; } void sum(){ int a, b, total ; printf("\nEnter any two numbers ") ; scanf("%d %d", &a, &b) ; total = a + b ; printf("\n Sum = %d \n", total ) ; }
Output
Enter any two numbers 2 3 Sum = 5 Press any key to continue . . .
Take Nothind Return Something
Program
#include void main( ) { int return_sum; return_sum=sum() ; printf("\n Sum = %d \n", return_sum ) ; } int sum(){ int a, b, total ; printf("\nEnter any two numbers " ) ; scanf("%d %d", &a, &b) ; total = a + b ; return total; }
Output
Enter any two numbers 2 3 Sum = 5 Press any key to continue . . .
Take Something Return Nothing
Program
#include void main( ) { int a, b, total ; printf("\nEnter any two numbers " ) ; scanf("%d %d", &a, &b) ; sum(a, b) ; } void sum(x, y){ int d ; d = x + y ; printf("\n Sum = %d \n", d ) ; }
Output
Enter any two numbers 2 3 Sum = 5 Press any key to continue . . .
Take Something Return Something
Program
#include void main( ) { int a, b, total ; printf("\nEnter any two numbers " ) ; scanf("%d %d", &a, &b) ; total = sum(a, b) ; printf("\n Sum = %d \n", total ) ; } int sum(x, y){ int d ; d = x + y ; return d; }
Output
Enter any two numbers 2 3 Sum = 5 Press any key to continue . . .
Scope Rule of Functions
Look at the following program
Program
#include void main() { int i = 20 ; message(i) ; } void message(int j) { int k = 35 ; printf("\n%d", j) ; printf("\n%d\n", k) ; }
Program
20 35 Press any key to continue . . .
In this program is it necessary to pass the value of the variable i to
the function message( )
? Will it not become automatically available
to the function message( )
? No. Because by default the scope of a
variable is local to the function in which it is defined. The presence
of i is known only to the function main( ) and not to any other
function. Similarly, the variable k is local to the function
message( )
and hence it is not available to main( ). That is why to
make the value of i available to message( )
we have to explicitly
pass it to message( )
. Likewise, if we want k to be available to
main( ) we will have to return it to main( ) using the return
statement. In general we can say that the scope of a variable is
local to the function in which it is defined.