Where is the C auto keyword used?

c
Vijay picture Vijay · Feb 3, 2010 · Viewed 92k times · Source

In my college days I read about the auto keyword and in the course of time I actually forgot what it is. It is defined as:

defines a local variable as having a local lifetime

I never found it is being used anywhere, is it really used and if so then where is it used and in which cases?

Answer

Jerry Coffin picture Jerry Coffin · Feb 3, 2010

If you'd read the IAQ (Infrequently Asked Questions) list, you'd know that auto is useful primarily to define or declare a vehicle:

auto my_car;

A vehicle that's consistently parked outdoors:

extern auto my_car;

For those who lack any sense of humor and want "just the facts Ma'am": the short answer is that there's never any reason to use auto at all. The only time you're allowed to use auto is with a variable that already has auto storage class, so you're just specifying something that would happen anyway. Attempting to use auto on any variable that doesn't have the auto storage class already will result in the compiler rejecting your code. I suppose if you want to get technical, your implementation doesn't have to be a compiler (but it is) and it can theoretically continue to compile the code after issuing a diagnostic (but it won't).

Small addendum by kaz:

There is also:

static auto my_car;

which requires a diagnostic according to ISO C. This is correct, because it declares that the car is broken down. The diagnostic is free of charge, but turning off the dashboard light will cost you eighty dollars. (Twenty or less, if you purchase your own USB dongle for on-board diagnostics from eBay).

The aforementioned extern auto my_car also requires a diagnostic, and for that reason it is never run through the compiler, other than by city staff tasked with parking enforcement.

If you see a lot of extern static auto ... in any code base, you're in a bad neighborhood; look for a better job immediately, before the whole place turns to Rust.