Variable Names in C code… | Accidental Scientist

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 Simon Cooke

Simon Cooke is a video game developer, ex-freelance journalist, screenwriter, film-maker and all-round good egg 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.
facebook comments
blog comments

2 Responses to Variable Names in C code…

  1. Anonymous says:

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

  2. The Daring Dragoon says:

    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. 🙂