I’m currently reading "Expert C Programming – Deep C Secrets", and just came into this :
The storage class specifier auto is never needed. It is mostly meaningful to a compiler-writer
making an entry in a symbol table — it says "this storage is automatically allocated on entering the
block" (as opposed to statically allocated at compiletime, or dynamically allocated on the heap). Auto
is pretty much meaningless to all other programmers, since it can only be used inside a function, but
data declarations in a function have this attribute by default.
I saw that someone asked about the same thing here, but they have no answer and the link given in comments only explains why there’s such a keyword in C, inherited from B, and the differences with C++11 or pre-C++11.
I’m posting anyways to focus on the part stating that auto
keyword is somehow useful in compiler-writing, but I can’t grasp the idea nor the connection with a symbol table, can someone help me please ?
I really insist on the fact that I ask only about compiler-writing usage.
EDIT :
To clarify, I asked this question because I’d like to know if there’s an example of code where auto
can be justified, because the author stated there would be, when writing compilers.
Here the whole point is that I think to have understood auto (herited from B, which was mandatory, useless in C), but I can’t imagine any example when using it is useful (or at least not useless).
It really seems that there’s no reason at all to use auto
, but if someone has an old source code or something like that corresponding to the quoted statements, it would be interesting to see.
>Solution :
As far as I can tell from 40+ years of C programming, including compiler work, the auto
keyword is completely useless in C.
It is used in C++ to enable type inference, where the compiler detects the type of a variable (with or without automatic storage) from the type of its initializer.
With the current trend pushing for convergence on a common subset for the C and C++ language, it is possible that a future C standard could add these semantics to variable definitions, but thankfully this does not seem to be in the pipe yet.
I actually have seen it used in proficiency tests, where the candidate is asked to find why this code does not compile:
#include <stdio.h>
#include <string.h>
int main(void) {
char word[20];
int auto = 0;
while (scanf("%19s", line) == 1) {
if (!strcmp(word, "car")
|| !strcmp(word, "auto")
|| !strcmp(word, "automobile"))
auto++;
}
printf("cars: %d\n", auto);
return 0;
}