twitter
    Find out what I'm doing, Follow Me :)

Now To Confess A Little Lie

I told you a short time ago that the only way to get a value back to the main program was through use of a global variable, but there is another way which we will discuss after you load and display the file named squares.c.
In this file we will see that it is simple to return a single value from a called function to the calling function. But once again, it is true that to return more than one value, we will need to study either arrays or pointers.

main( ) /* This is the main program */
{
int x,y;
for(x = 0;x < 7;x++) {
y = squ(x); /* go get the value of x*x */
printf("The square of %d is %d\n",x,y);
}
for (x = 0;x <= 7;++x)
printf("The value of %d is %d\n",x,squ(x));
}
squ(in) /* function to get the value of in squared */
int in;
{
int square;
square = in * in;
return(square); /* This sets squ() = square */
}



In the main program, we define two integers and begin a "for" loop which will be executed 8 times. The first statement of the for loop is "y = squ(x);", which is a new and rather strange looking construct. From past experience, we should have no trouble understanding that the "squ(x)" portion of the statement is a call to the "squ" function taking along the value of "x" as a variable. Looking ahead to the function itself we find that the function prefers to call the variable "in" and it proceeds to square the value of "in" and call the result "square". Finally, a new kind of a statement appears, the "return" statement. The value within the parentheses is assigned to the function itself and is returned as a usable value in the main program. Thus, the function call "squ(x)" is assigned the value of the square and returned to the main program such that "y" is then set equal to that value. If "x" were therefore assigned the value 4 prior to this call, "y" would then be set to 16 as a result of this line of code.

Another way to think of this is to consider the grouping of characters "squ(x)" as another variable with a value that is the square of "x", and this new variable can be used any place it is legal to use a variable of its type. The value of "x" and "y" are then printed out. To illustrate that the grouping of "squ(x)" can be thought of as just another variable, another "for" loop is introduced in which the function call is placed in the print statement rather than assigning it to a new variable.

One last point must be made, the type of variable returned must be defined in order to make sense of the data, but the compiler will default the type to integer if none is specified. If any other type is desired, it must be explicitly defined. How to do this will be demonstrated in the next example program.

Compile and run this program.