From the C Relic File: auto

Of all the C language keywords you don’t use, auto is probably the most memorable. That’s because it’s listed first among the canonical table of 32 C language keywords. Yet, in all the code you’ve written or seen, auto is seldom used if at all. So what does it do and is it even necessary?

First, a note to the nerds: Yes, I know, in the C11 standard, the first keyword is _Alignas. Even today, when you see the C language keywords listed, most resources show auto first. And few keyword tables list all the underscore keywords.

Second, auto is officially known as a storage class specifier. The C language has five of them:

  • auto
  • register
  • static
  • extern
  • typedef

All variables you declare in a function without using a storage class specifier are assumed to be auto. That’s why you don’t see it used; it’s set automatically. And this definition is important: auto is used only within a function. You cannot create an global auto variable, one that exists outside of a function. Those are extern storage class variables.

In a way, you can think of the auto class as the opposite of the static class. A static variable type is one thats value is retained when a function is done; auto variable values are released.

Third, some programmers may claim that auto is a synonym for an int variable. It’s not. The int variable type is the default for C. So if you use a declaration such as:

auto x;

What you’re specifying is:

auto int x;

Or really:

int x;

Each of these three statements is processed identically by the compiler, though auto x; generates a warning that an int variable is assumed.

I’ve mused for a while on which code to present as an example in this Lesson. Because auto is applied to any variable type in a function that doesn’t have register, static, extern, or typedef before it, an example is pointless. This raises the question of whether auto is necessary. It’s not! You can code with it or without it. In fact, leaving it off is the best course — unless you want to confuse someone by sticking a random auto in your code.

By the way, the register keyword is similar to auto. It follows the same rules, though register stipulates that the variable is used frequently. Further, you cannot use the & (address-of) operator with a register class variable.

In the olden days, register may have directed the compiler to use a processor register to store an integer value. I’m not sure whether that’s implemented today or even if such action would noticeably improve program performance.

Leave a Reply