Your browser doesn't support JavaScript Functions – Windows Programming

Functions

A function is a unit of code grouped to perform a specific task.  Functions provide a way to compartmentalise and organise a program. Functions are identified by a name, enclosed within scope braces ({}) and may be terminated by a return statement. On calling a function the execution of the program branches to the first statement in that function and continues until it reaches a return statement or the last statement of the function; at that point, execution resumes at the place where the function was called. A function can have multiple parameters separated by commas, but it can have only one return type. A function that does not need to return a value is declared void.  In C, one function cannot be embedded within another function.

Function Prototype

The function prototype declares a function before its definition and details its name, the list of parameters the function accepts and the return type of the function. The compiler needs to know this information before the function is called. A function defined before main() (forward declaration) does not need a function prototype. The variables passed to a function are called arguments, and are enclosed in parentheses following the function’s name. A function declaration inside main(), has its scope limited to within the main{} block, however, if you add it outside main, its scope is the entire source file. 

Function call

A program cannot execute the function statements until called by another part of the program. A function call is an expression that passes control and arguments (if any) to a function. When a function declaration contains parameters, the function call must send arguments. Arguments are values the function requests within its parameter list. Except for those functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. When the function is finished, execution control passes to the place from which the function was called.

Function Parameters

The purpose of parameters is to allow functions to receive arguments.  Multiple parameters are separated by a comma. These parameters don’t have to be of the same data type. Any valid C expression can be a function parameter, including constants, logical expressions, and other functions that return a value. Parameter data can be passed into and out of methods and functions using pass-by-value or pass-by-reference.

Pass by Value – means that the value of an argument is copied into the corresponding function parameter. The parameter is a separate variable within the called function. Any changes made to the parameter inside the function affect only that local copy and do not change the original variable.

Passing by Pointer – C does not support true pass-by-reference parameters. However, a pointer can be passed to a function by value. The function can then use the pointer to modify the original object.

The following code demonstrates passing by pointer and passing by value by passing two values to two different functions and attempting to swap them.

When a and b are passed by pointer, the functions receive their addresses and can modify the original variables. When they are passed by value, copies of the values are supplied to the function, so changes made to the parameters do not affect the original variables.

#include <stdio.h>

void swapByPointer(int *x, int *y);  /* function declaration */
void swapByValue(int x, int y);      /* function declaration */

int main()
{
    int a = 10, b = 20;
    printf("Before swap by pointer: %d %d\n", a, b);
    swapByPointer(&a, &b);/* pass addresses of a and b */
    printf("After swap by pointer:  %d %d\n", a, b);
    printf("Before swap by value:   %d %d\n", a, b);
    swapByValue(a, b);/* pass copies of a and b */
    printf("After swap by value:    %d %d\n", a, b);
    return 0;
}

/* Swap by pointer */
void swapByPointer(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Swap by value */
void swapByValue(int x, int y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

Passing an Array of Values to a Function

When an array is passed to a function it is always treated as a pointer by that function.  Pointers to an array are passed as an argument by specifying the array’s name without an index. The argument represents the memory address of the first element of an array. Any changes in the function will therefore be reflected in the original array. To pass a single-dimension array as an argument in a function use one of the following.

void myFunction(int *param) array passed as pointer
void myFunction(int param[10]) array passed a sized array
void myFunction(int param[]) array passed as unsized array

All these variants are functionally identical. Each effectively tells the compiler that an integer pointer will be received.

The following simple function demonstrates how to pass a char array and int value to a procedure.

#include <stdio.h>

float total(float value[], int size);  /* function prototype */

int main()
{
    float measurement[] = {223.1, 555, 22.63, 3.12, 31.5, 180};
    printf("Total Values = %.2f\n", total(measurement, 6));   /* function call passes the array and its size */
     return 0;
}

float total(float value[], int size)  /* function definition */
{
    int i;
    float total = 0.0;
    for (i = 0; i < size; ++i)
    {
        total += value[i];
    }
    return total;
}

Functions That Have a Variable Number of Arguments

A variable-length argument list allows a function to accept a varying number of arguments.

When a function is declared with a variable argument list, at least one fixed parameter must be declared first, followed by an ellipsis (...) to indicate that additional arguments may be supplied.

For example:

int sum(int count, ...);

Here, count is the fixed parameter, while … represents the additional arguments.

The macros and types provided by the stdarg.h header file are used to access the arguments in the variable argument list. These include:

va_end() – A macro used when processing of the variable argument list is complete. It performs any necessary cleanup associated with the va_list object.
va_list – A type used to hold the information required to access the individual arguments in the variable argument list.
va_start() – A macro used to initialise a va_list object so that it can be used to access the first variable argument.
va_arg() – A macro used to retrieve the next argument from the variable argument list. The type of the argument being retrieved must be specified.

For example

#include <stdarg.h>
#include <stdio.h>

// This function sums the specified number of integers.
int sumvalues(int count, ...)
{
    int i, sum;
    va_list ap;// holds information needed to access variable arguments
    va_start(ap, count);// initialise the variable argument list
    sum = va_arg(ap, int);// retrieve the first variable argument
    // Retrieve the remaining arguments and add them to the total.
    for (i = 2; i <= count; i++)
    {
        sum = sum + va_arg(ap, int);
    }
    va_end(ap); // finish processing the variable argument list
    return sum;
}

int main()
{
    int count = 5;
    printf("Sum of values is %d\n",
           sumvalues(count, 12, 67, 6, 7, 100));
    return 0;
}

The output is:

Sum of values is 192

Here, count tells sumvalues() how many additional arguments it must retrieve. The call:

sumvalues(count, 12, 67, 6, 7, 100);

passes 5 as the fixed argument, followed by five variable arguments. va_arg() is then used to retrieve each integer in sequence.

One important point is that C has no built-in way for a variadic function to determine how many arguments were supplied. The function therefore needs another mechanism, such as the count parameter in this example, to know how many arguments to retrieve.

Returning a Value from a Function

A function can return a value or return no value by using the void return type. To return a value from a function, the return keyword is followed by an expression whose value is returned to the calling code. A function’s return value can also be used directly in an expression or passed as an argument to another function. If the return value is not used, the value is simply discarded. A function can contain multiple return statements, but each execution of the function can return only one value. Multiple return statements can be used to return different values depending on the program’s logic. After a return statement, program execution continues immediately after the statement that called the function.

Recursion

A function that calls itself is known as a recursive function. The recursion proceeds until some condition is met which breaks the recursive cycle. The following simple recursion function demonstrates how a countdown procedure calls itself until the exit condition is met.

#include <stdio.h>

void printFun(int countp)
{
    if (countp < 1)              // base case: stop when countp is less than 1
        return;
    printf("Count value = %d\n", countp);
    printFun(countp - 1);        // recursive call
}

int main()
{
    int count = 3;
    printFun(count);             // call the recursive function
    return 0;
}

Returns the following

Count value = 3
Count value = 2
Count value = 1

The first call passes 3 to printFun(). The function prints the value and then calls itself with countp – 1. This continues until countp becomes 0. At that point, the if condition is true and the return statement stops the recursion.