Variable Names in C code...

Someone over at the MSDN blogs recently posted a mini-rant about people using inscrutable variable names in short apps...

He mentioned that some people use things like i, and others use random letters like x. Believe it or not, there is actually some structure and reasoning behind these choices of variable names, and a certain amount of historical convention to it.

Reasons for using i, j, k as loop variable names:

These are mathematical (or engineering) index variables. Typically you'll see them used in matrices. i indicates the row, j the column, and k? Well, you get the idea.

Reasons for using x, y, z as loop variable names:

These are used when you're iterating over space - x indicates going across a row of pixels / space, and y indicates going vertically down that row of pixels / space. z, of course, goes into the page.

The only other version I've seen is l,m,n - used on the Sinclair Spectrum, because hitting the L key the first time gives you the token for the BASIC FOR command, whereas hitting it the second time gives you L - which is handy as you can rationalize it as "loop variable".

Using i, ii, iii is, however, incorrigible and encourages errors - any repeated single-letter name is going to give you trouble, as you can easily misread it.

Using i, ii, iii, iv, v, vi, vii, viii, ix, x, however, will lead to you being cudgeled to death with a sundial by a software engineer.

About the author

Simon Cooke is an occasional video game developer, ex-freelance journalist, screenwriter, film-maker, musician, and software engineer in Seattle, WA.

The views posted on this blog are his and his alone, and have no relation to anything he's working on, his employer, or anything else and are not an official statement of any kind by them (and barely even one by him most of the time).

Archived Wordpress comments
Anonymous wrote on Saturday, January 29, 2005:

You’ve forgotten your Spectrum keyboard layout; FOR was on the F key, LET was on the L key.

The Daring Dragoon wrote on Sunday, April 30, 2006:

The genesis of using i/j/k for iteration is actually a holdover from Fortran. Apparently, Fortran enforced variable types based on variable symbol names, and i, j, and k were all preordained as integers. Given that you generally don’t iterate using reals, i, j, and k natually became ingrained in all programmers of the day as the index/iteration variables.

I’ve written exactly one thing in Fortran because they made us do it in college, so my facts may be a bit off. …but it sure made sense when I wrote it. :-)

facebook comments