Vincent Gable’s Blog

May 24, 2010

Never Name a Variable “Index”

Filed under: Bug Bite,C++,Cocoa,Objective-C,Programming | ,
― Vincent Gable on May 24, 2010

Never name a variable index, especially in C.

Instead say what it indexes. For example, if it is used to index an array of Foo objects, call it fooArrayIndex, or currentFooIndex.

If the index variable is just used to enumerate over a collection of objects, (eg. for(int i = 0; i < arraySize; i++){…} ) then iterate smarter, using a simpler construct that doesn’t require declaring auxiliary variables. (Eg., in Objective-C use Fast Enumeration). It’s not always possible to do this, but it’s always a good idea to try.1

Why index is Especially Bad in C

The standard strings.h header declares a function named index, that finds the first occurrence of a charicter in a C-string. In practical terms every C program will have the index function declared everywhere.

But when a variable is declared with the name index it shadows the function — meaning the local variable named index takes over the name index, so the function can’t be called anymore:

char * world = index("Hello, World", 'W');
NSLog(@"'%s'", world);

Prints “‘World'”, but

int index = 0;
char * world = index("Hello, World", 'W');
NSLog(@"'%s'", world);

Won’t compile, because an int isn’t a function.

Obviously this is a problem for code that uses the index() function — but honestly modern code probably uses a safer, unicode-aware string parsing function instead. What’s given me the most trouble is that shadowing index makes the compiler give lots of bogus warnings, if you have the useful GCC_WARN_SHADOW warning turned on.

There are other good reasons as, specific to Objective-C, which Peter Hosey covers.

1If you really can’t think of a better name than “index”, I prefer the more terse i. It sucks, but at least it’s shorter. Brevity is a virtue.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Powered by WordPress