Functions in C

The two things which are executed every loop (apart from the fgets itself) are a call to a function called calculate, which actually performs the polish postfix computation (or at least it will once we actually finish writing the function) and a printf statement to display a new prompt, ready for the next input from the user.

We have already used functions in C, but they have all been functions from the standard libraries. But there is no standard library function to do a polish postfix calculation, so we have to write this function ourselves. The function itself is given immediately before the main part of the program. At the moment it does nothing and just returns back to the main program after it is called.

The void simply says that there is no return value from our function. For readers familiar with other programming languages like Pascal and Basic, this is equivalent to what is known as a procedure or subroutine respectively. In C, procedures and functions are all treated the same way, just that a procedure is a function with no return value.

Immediately after the name of the function calculate, a list of input parameters is given between parentheses. This is what the function expects to be given as input. In our case we tell it to expect a pointer to a char, which for the internal benefit of the function, will be given the name inString (we gave it the same name as our buffer inString that is used in the main program, but we did not have to call it the same thing). This input parameter can be thought of as a temporary variable, created each time the function is called, which will be set to contain some piece of input to the function when the function is called.

Recall that the name of an array is a pointer to the first element of that array, which in the case of our buffer inString, is of type char. Thus the way we have specified our function parameter, we can actually call our function with the name of an array of characters as an input parameter. This is precisely what is done down in the main program. We call calculate with the name of our buffer, inString, as an input parameter. Basically, this is the way we pass an array as a parameter to a function.

If we wanted to have a function which took more parameters, we would just include them in the function definition between the parentheses, separated by commas.

The program above actually runs, although of course at this stage it doesn't do much except prompt the user for input and accept anything, except a quit, which it responds to by terminating. In the next lesson we will begin to fill in the details of the calculate function.