What is the usefulness of the auto keyword in C?

1
The keyword auto , defined by the C language, is an old keyword and seemingly useless in language. I know that in C its function is to define that it should be stored in the stack as a local variable whose life ends with the end of the scope in which it was declared. I also know what it does in C ++, although this is not the case.

This keyword is really necessary and has some real utility for the language. It seems to me useless, since all C-scope variables are stored in the stack , and only through the use of specific functions can heap be used.

I remember reading something about macros that might make the keyword auto needed, but I do not know if this really has anything to do with my question.     

asked by anonymous 30.04.2017 / 18:34

2 answers

2

The auto keyword was included in the C language because it was the keyword to declare local variables in the C predecessor, Language B - and yes, I'm serious. Since B had no types, a definition of a variable needed to be preceded by either auto or extrn (equivalent to extern C).

Since at the beginning of C there was a need to port a quantity of code B to C, the auto keyword was included to reduce the workload of these carriers (another characteristic was the possibility of specifying functions without a type such as main() { /* ... */ } and have them return int implicitly).

    
03.05.2017 / 22:41
5

None.

Ok, technically it indicates where the variable will be stored, just like static and extern can be used. Only it can only be used within function. And if you do not use anything inside the function the declared variable will be local, which is the same as auto indicates. So its practical utility is null.

In fact in macro it can be useful to prevent the variable from being declared as static , but if you create a variable in a macro, you may be abusing the feature.

If you want to keep code compatibility with C ++ 11 up, then do not use. C ++ 11 specified another use for this keyword allowing type inference.

That is, your rating is correct.

    
30.04.2017 / 18:39