Feb 062016
 

I just came across this gem of an example of bad coding in the C language.

Most C implementations allow arrays as function arguments. What is less evident (unless you actually bothered to read the standard, or at least, your copy of Kernighan and Ritchie from cover to cover) is that array arguments are silently converted to pointers. This can lead to subtle, difficult-to-spot, but deadly programming errors.

Take this simple function, for instance:

void fun(int arr[100])
{
    printf("REPORTED SIZE: %d\n", sizeof(arr));
}

Can you guess what its output will be? Why, arr is declared as an array argument of 100 ints, so the output should be, on most systems, 400 (ints being 4 bytes in length), right?

Not exactly. Let me show you:

int main(int argc, char *argv[])
{
    int theArr[100];

    printf("THE REAL SIZE: %d\n", sizeof(theArr));
    fun(theArr);
    return 0;
}

On a 64-bit Linux box, this program compiles cleanly, and produces the following output:

THE REAL SIZE: 400
REPORTED SIZE: 8

Similarly, on Windows, using a 32-bit version of Microsoft’s C compiler, I once again get a clean compile and the program outputs this:

THE REAL SIZE: 400
REPORTED SIZE: 4

The morale of this story: Array arguments are pure, unadulterated evil. Avoid them when possible. They offer no advantage over pointer arguments, but they can badly mislead even the most experienced programmer. Compilers still allow array arguments, mainly for historical/compatibility reasons I guess, but it is unconscionable that they don’t even provide a warning when this abuse of syntax happens.

 Posted by at 9:45 am