Where is the C auto keyword used?
Asked Answered
C

9

142

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?

Croteau answered 3/2, 2010 at 14:22 Comment(0)
B
131

auto is a modifier like static. It defines the storage class of a variable. However, since the default for local variables is auto, you don't normally need to manually specify it.

This page lists different storage classes in C.

Blastoff answered 3/2, 2010 at 14:23 Comment(4)
Was just looking at this again after somebody up-voted my answer. You say you "don't normally need to manually specify it." I just have to ask: is there actually a circumstance in which auto can be specified but won't happen by default?Manifesto
@JerryCoffin Not in C. In C++11, it is repurposed and you can use it to effectively get local variable type inference.Blastoff
One possible use is in forward declaration of nested functions in GNU C - although this is a hijacking of the original definition of auto. tigcc.ticalc.org/doc/keywords.html#autoCollincolline
The page linked is outdated. Since C11, there's also _Thread_local details: en.cppreference.com/w/c/language/storage_duration and https://mcmap.net/q/161409/-_thread_local-storage-class-specifier-in-cLoo
M
196

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.

Manifesto answered 3/2, 2010 at 14:51 Comment(7)
I recently passed a serious conflagration (closed two lanes) that suggests a need for char auto my_car;Audrieaudris
Actually, in Rust it would be extern const static auto my_car.Mcwilliams
Why confuse readers by 'car' name?Barmecide
not to be confused with CDRRenayrenckens
I find this answer very confusing.Gallenz
@MehdiCharife: "... 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."Manifesto
I feel pretty dumb; only after having revisited this post a few weeks later now do I get that "auto" can also stand for "automobile" :-)Lemniscus
B
131

auto is a modifier like static. It defines the storage class of a variable. However, since the default for local variables is auto, you don't normally need to manually specify it.

This page lists different storage classes in C.

Blastoff answered 3/2, 2010 at 14:23 Comment(4)
Was just looking at this again after somebody up-voted my answer. You say you "don't normally need to manually specify it." I just have to ask: is there actually a circumstance in which auto can be specified but won't happen by default?Manifesto
@JerryCoffin Not in C. In C++11, it is repurposed and you can use it to effectively get local variable type inference.Blastoff
One possible use is in forward declaration of nested functions in GNU C - although this is a hijacking of the original definition of auto. tigcc.ticalc.org/doc/keywords.html#autoCollincolline
The page linked is outdated. Since C11, there's also _Thread_local details: en.cppreference.com/w/c/language/storage_duration and https://mcmap.net/q/161409/-_thread_local-storage-class-specifier-in-cLoo
K
73

The auto keyword is useless in the C language. It is there because before the C language there existed a B language in which that keyword was necessary for declaring local variables. (B was developed into NB, which became C).

Here is the reference manual for B.

As you can see, the manual is rife with examples in which auto is used. This is so because there is no int keyword. Some kind of keyword is needed to say "this is a declaration of a variable", and that keyword also indicates whether it is a local or external (auto versus extrn). If you do not use one or the other, you have a syntax error. That is to say, x, y; is not a declaration by itself, but auto x, y; is.

Since code bases written in B had to be ported to NB and to C as the language was developed, the newer versions of the language carried some baggage for improved backward compatibility that translated to less work. In the case of auto, the programmers did not have to hunt down every occurrence of auto and remove it.

It's obvious from the manual that the now obsolescent "implicit int" cruft in C (being able to write main() { ... } without any int in front) also comes from B. That's another backward compatibility feature to support B code. Functions do not have a return type specified in B because there are no types. Everything is a word, like in many assembly languages.

Note how a function can just be declared extrn putchar and then the only thing that makes it a function that identifier's use: it is used in a function call expression like putchar(x), and that's what tells the compiler to treat that typeless word as a function pointer.

Kattegat answered 19/6, 2014 at 19:19 Comment(0)
M
35

In C auto is a keyword that indicates a variable is local to a block. Since that's the default for block-scoped variables, it's unnecessary and very rarely used (I don't think I've ever seen it use outside of examples in texts that discuss the keyword). I'd be interested if someone could point out a case where the use of auto was required to get a correct parse or behavior.

However, in the C++11 standard the auto keyword has been 'hijacked' to support type inference, where the type of a variable can be taken from the type of its initializer:

auto someVariable = 1.5;   // someVariable will have type double

Type inference is being added mainly to support declaring variables in templates or returned from template functions where types based on a template parameter (or deduced by the compiler when a template is instantiated) can often be quite painful to declare manually.

Mossy answered 3/2, 2010 at 15:52 Comment(2)
“the variable is local to a block” — that's not at all true. All variables declared in a block are local to that block (with respect to scope). They might be linked to other variables in the program, but the declaration is only visible in that block. auto is about storage class which has nothing to do with visibility.Flattop
Thank you for explaining the difference in C++. I've only seen it used for type inference in C++, so I was confused when I saw it was a keyword in C, too.Sb
K
20

With the old Aztec C compiler, it was possible to turn all automatic variables to static variables (for increased addressing speed) using a command-line switch.

But variables explicitly declared with auto were left as-is in that case. (A must for recursive functions which would otherwise not work properly!)

Kiwi answered 16/11, 2016 at 13:46 Comment(0)
J
13

The auto keyword is similar to the inclusion of semicolons in Python, it was required by a previous language (B) but developers realized it was redundant because most things were auto.

I suspect it was left in to help with the transition from B to C. In short, one use is for B language compatibility.

For example in B and 80s C:

/* The following function will print a non-negative number, n, to
   the base b, where 2<=b<=10.  This routine uses the fact that
   in the ASCII character set, the digits 0 to 9 have sequential
   code values.  */

printn(n, b) {
        extern putchar;
        auto a;

        if (a = n / b)        /* assignment, not test for equality */
                printn(a, b); /* recursive */
        putchar(n % b + '0');
}
Juieta answered 3/5, 2017 at 23:23 Comment(1)
What do you mean by the remark about Python? Semicolons in Python are there to separate statements on a single line like a = 42; b = 23. Has nothing to do with any previous language and they are not redundant.Wilkinson
I
5

auto can only be used for block-scoped variables. extern auto int is rubbish because the compiler can't determine whether this uses an external definition or whether to override the extern with an auto definition (also auto and extern are entirely different storage durations, like static auto int, which is also rubbish obviously). It could always choose to interpret it one way but instead chooses to treat it as an error.

There is one feature that auto does provide and that's enabling the 'everything is an int' rule inside a function. Unlike outside of a function, where a=3 is interpreted as a definition int a =3 because assignments don't exist at file scope, a=3 is an error inside a function because apparently the compiler always interprets it as an assignment to an external variable rather than a definition (even if there are no extern int a forward declarations in the function or in the file scope), but a specifier like static, const, volatile or auto would imply that it is a definition and the compiler takes it as a definition, except auto doesn't have the side effects of the other specifiers. auto a=3 is therefore implicitly auto int a = 3. Admittedly, signed a = 3 has the same effect and unsigned a = 3 is always an unsigned int.

Also note 'auto has no effect on whether an object will be allocated to a register (unless some particular compiler pays attention to it, but that seems unlikely)'

Inbound answered 27/3, 2020 at 16:23 Comment(0)
E
1

Auto keyword is a storage class (some sort of techniques that decides lifetime of variable and storage place) example. It has a behavior by which variable made by the Help of that keyword have lifespan (lifetime ) reside only within the curly braces

{
    auto int x=8;        
    printf("%d",x);  // here x is 8

    { 
        auto int x=3;
        printf("%d",x);  // here x is 3
    }              

    printf("%d",x);  // here x is 8
}          
Eighteen answered 20/10, 2015 at 13:22 Comment(1)
You don't need auto for this. You can also just use int x in both cases, will still work. At least with gcc (Debian 8.3.0-6) 8.3.0.Carcinomatosis
R
-2

I am sure you are familiar with storage class specifiers in C which are "extern", "static", "register" and "auto". The definition of "auto" is pretty much given in other answers but here is a possible usage of "auto" keyword that I am not sure, but I think it is compiler dependent. You see, with respect to storage class specifiers, there is a rule. We cannot use multiple storage class specifiers for a variable. That is why static global variables cannot be externed. Therefore, they are known only to their file. When you go to your compiler setting, you can enable optimization flag for speed. one of the ways that compiler optimizes is, it looks for variables without storage class specifiers and then makes an assessment based on availability of cache memory and some other factors to see whether it should treat that variable using register specifier or not. Now, what if we want to optimize our code for speed while knowing that a specific variable in our program is not very important and we dont want compiler to even consider it as register. I though by putting auto, compiler will be unable to add register specifier to a variable since typing "register auto int a;" OR "auto register int a;" raises the error of using multiple storage class specifiers. To sum it up, I thought auto can prohibit compiler from treating a variable as register through optimization.

This theory did not work for GCC compiler however I have not tried other compilers.

Roundworm answered 22/7, 2020 at 8:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.