Wednesday 13 February 2013

Returning Values from a Function in C programming



Just as data can be passed to a function, so also, data can be passed back from a called function to its caller.

In C, functions can return values through the return verb as illustrated in the following example:

main()
{
int x, y, value;
scanf("%d %d", &x, &y);
fflush(stdin);
value = sun(x,y);
printf("Total is %d \n", vlaue);
}
sum (a,b)
int a,b;
{
return a + b;
}

In this example, the function sum() sends back the value of a + b to the function main(). The value returned to main() from sum() is stored in a variable called value, the value of which is printed out through the printf() statement in main().

The return statement not only sends back a value to a caller function, but also returns control to it.

Note that a function can return only one value, though it may return different values depending on certain conditions.

C assumes that the value  returned is an int type value. In case a function has to return a value which is not an integer, then the function itself has to be declared of the specific data type that it returns.

0 comments:

Post a Comment

Powered by Blogger.