C Tutorial (32) : Returning values from functions & function prototype

This tutorial completes the multiple-function picture by showing you how to return values from the called function to the calling function. It also explains function prototypes. You will now understand why most programs contain this line:

return 0;

You also will understand the true purpose of header files.

Returning Values

When a function is to return a value, use the return statement to return the value.

Note : If a function doesn’t return a value, a return statement isn’t needed because the function will return to the calling function automatically. Nevertheless, if you need to return a value, a return statement is required.

Although you can pass several arguments to functions, you can return only one value to the calling function.

c_func_return

               You can pass more than one value but return only one.

Although a single return value might seem limiting, it really isn’t. As a matter of fact, none of the built-in functions returns more than a single value, and neither can yours.

Note : The gets() function seems as if it returns more than one value because it returns a character string array. Remember, though, that an array name is nothing more than a pointer to the array’s first position. Therefore, gets() actually returns a character pointer that points to the beginning of the string the user entered.

The following program contains a function that receives three floating-point values: test1, test2, and test3. The function named gradeAve() calculates the average of those three grades and then returns the answer.

/* The program demonstrates functions returning a value by passing 
   three floating-point numbers (grades) and calculating the average 
   of the three. */

#include <stdio.h>

float gradeAve(float test1, float test2, float test3);

main()
{
float grade1, grade2, grade3; 
float average;

printf("What was the grade on the first test? "); 
scanf(" %f", &grade1);

printf("What was the grade on the second test? "); 
scanf(" %f", &grade2);

printf("What was the grade on the third test? "); 
scanf(" %f", &grade3);

//Pass the three grades to the function and return the average
average = gradeAve(grade1, grade2, grade3);

printf("\nWith those three test scores, the average is %.2f", average);

return 0;
}

/******************************************************************/

float 
gradeAve(float test1, float test2, float test3) 
// Receives the values of three grades
{
float localAverage;

localAverage = (test1+test2+test3)/3;
return (localAverage); // Returns the average to main
}

Here is sample output from this program:

What was the grade on the first test? 95
What was the grade on the second test? 88
What was the grade on the third test? 91
With those three test scores, the average is 91.33.

Note : Notice that main() assigned the gradeAve() return value to average. main() had to do something with the value that was returned from gradeAve().

You can put an expression after return as well as variables. This:

sales = quantity * price; 
return (sales);

is identical to this:
return (quantity * price);

The return Data Type

At the beginning of the gradeAve() function, you see float. float is the data type of the returned value localAverage. You must put the return data type before any function name that returns a value. If the function returned a long int, long int would have to precede the function name.

If you don’t specify a return data type, C assumes int. Therefore, C expects that every function without a return data type specified explicitly will return int. Both of these functions’ first lines mean exactly the same thing to C:

int myFun(int a, float x, char c)
and
myFun(int a, float x, char c)      /* int is assumed */

Note : Even main() is assumed to return an int value unless you specify an overriding return data type. That is why you’ve seen return 0; at the end of most of these programs! Because main() has no specified return data type, int is assumed, and the return 0; ensures that an int is returned to your operating system.

If your function doesn’t return a value, or if your function isn’t passed a value, you can insert the keyword void for either the return data type or the parameter list or both. Therefore, the first line of a function that neither gets any value nor returns any value might look like this:

void doSomething(void)      /* Neither is passed nor returns */

Note : main() can’t be of type void if you use strict American National Standards Institute (ANSI) C. It must be of type int. (However, most compilers—even those that promote themselves as ANSI C-compatible—enable you to specify void as main()’s return type.)

Prototype

Making a function work properly involves one last step. If a function returns any value other than int, you should prototype that function. Actually, you should prototype functions that return integers as well for clarity.

The word prototype means a model of something else. A prototype of a function is just a model of the actual function. At first, a C prototype seems like a total waste of time.

The reason functions that return int values don’t need prototypes is that int is the default prototyped return value unless you specify a different return value. Therefore, these two prototypes both model the same function:

int aFunc(int x, float y);    /* 2 passed, one integer returned */
and
aFunc(int x, float y);        /* 2 passed, one integer returned */

Prototypes aren’t required if you don’t return a value or if you return an integer value, but they are strongly recommended. When you prototype, C ensures that you don’t pass a float value to a function that expects to receive a char. Without the prototype, C tries to convert the float to a char, and a bad value is passed as a result.

To prototype a function, place an exact duplicate of the function’s first line somewhere before main(). If your program calls 20 functions, you should have 20 prototypes.

Prototype every function in your programs—every function called by your code and even the built-in functions such as printf(). You might wonder how you can prototype printf() when you didn’t write it to begin with. The file stdio.h contains a prototype for printf(), scanf(), getchar(), and many other input and output functions. The prototype for strcpy() appears in string.h. You should find out the name of the header file when you learn a new built-in function so that you can use the #include directive to add the file to your program and make sure that each function is prototyped.

Note : main() needs no prototype as long as you place main() as the first function in the program. main() is known as a self-prototyping function because no other functions call main() before it appears in the code.

The following program does not work correctly because the float return type is not prototyped correctly. Remember, C assumes that an int is returned (even if you return a different data type) unless you override the return type in the prototype.

#include <stdio.h>

compNet(float atomWeight, float factor);

main()
{
float atomWeight, factor, netWeight;

printf("What is the atomic weight? "); 
scanf(" %f", &atomWeight); 
printf("What is the factor? "); 
scanf(" %f", &factor);

netWeight = compNet(atomWeight, factor); 
printf("The net weight is %.4f\n", netWeight); 

return 0;
}

/************************************************************/
compNet(float atomWeight, float factor)
{
float netWeight;
netWeight = (atomWeight – factor) * .8; 

return(netWeight);
}

This shows the incorrect output:

What is the atomic weight? .0125
What is the factor? .98
The net weight is 0.0000

To fix the problem, you have to change the prototype to this:

float compNet(float atomWeight, float factor);

You also have to change the compNet()’s definition line (its first line) to match the prototype:

float compNet(float atomWeight, float factor)

Never pass or return a global variable if you use one. Global variables don’t have to be passed. Also, the parameter lists in the calling function, receiving function, and prototype should match in both numbers and data types.(The names of the values don’t have to match.)

Passing arguments/variables to functions  < Prev

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s