The cognitive load of C: functions

After teaching introductory programming in C for over a decade, it is clear to me that the problems with cognitive load and programming in C often manifest themselves clearest when novice programmers have to deal with functions and arrays.

The problems with functions in C do not really occur until there is a requirement to return more than one value from a function. Consider the C function below, which calculates the area of a circle, given the radius, and returns the area:

int areaCircle(double radius)
{
    return pi * radius * radius;
}

This is simple enough, because there is one input and one output. Now if we have a function that calculates the area and circumference of a circle, and attempts to return both:

int circleStats(double radius)
{
    double area, circ;
    area = pi * radius * radius;
    circ = 2.0 * pi * radius;
    return area, circ;
}

This will not work. So the novice programmer is now relegated to learning about the concept of pass-by-reference, and dealing with pointers. The above function would transform to:

void circleStats(double radius, double *area, double *circ)
{
    *area = pi * radius * radius;
    *circ = 2.0 * pi * radius;
}

Or maybe a combination of the two:

double circleStats(double radius, double *area)
{
    double circa;
    *area = pi * radius * radius;
    circ = 2.0 * pi * radius;
    return circ;
}

Either one is correct, but why force the novice programmer to learn about memory locations when performing a simple task like output from a function. They also have to learn about how the function is accessed. In the first case:

double r, a, c;
r=7.2;
circleStats(7.2, &a, &c);

This is further complicated by arrays, which because the lead element is already a pointer, do not require the same syntax – they are passed by reference by default. Functions in C can also only pass back single variables, or structs (or dynamic entities) – not arrays, which further increases the cognitive load. Other languages make this easier by using some form of tuples to aggregate the information being returned by the function. Here is the same function written in Python:

def circleStats(radius):
    area = 3.14159 * radius * radius
    circ = 2.0 * 3.14159 * radius
    return area, circ

which can be called in the following manner:

a,c = circleStats(3.8)

This is much easier for the novice programmer to learn, partially because it does not involve the programmer having to deal with memory and pointers.

Advertisements

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