What is the usefulness of auto keyword in C?

Asked

Viewed 806 times

1

To keyword auto, defined by the language C, is a keyword old and seemingly useless in the language. I know that in C its function is to define that it should be stored in 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.

That one keyword is really necessary and has some real use 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 is it possible to make use of the heap.

I remember reading something about macros that can make keyword self necessary, but I don’t know if this really has anything to do with my question.

2 answers

5

None.

Ok, technically it indicates where the variable will be stored, as well as static and extern can be used. Only it can only be used within function. And if you use nothing within the function the declared variable will be local, which is the same as the auto indicates. Then its practical usefulness is null.

In fact macro 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 resource.

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

That is, your assessment is correct.

  • None? Not even in older versions of the language? Has it been included in the language for future use? This would explain the lack of utility in versions prior to C++11, no?

  • 2

    I don’t really remember. I think I had reason to indicate to the compiler to put that in the register if he thought it was appropriate, as opposed to register that required doing so. Today every compiler makes this decision on its own without needing to specify anything, and even specifying is ignored.

2


The keyword auto was included in the C language because it was the keyword for declaring local variables in the predecessor of C, the b language - and yes, I am serious. As B had no types, a definition of a variable needed to be preceded or auto or of extrn (equivalent to extern of C).

As in the beginning of C there was a need to carry a quantity of code B to C, the keyword auto was included to reduce the workload of these carriers (another feature was the possibility to specify functions without a return type, such as main() { /* ... */ } and make them return int implicitly).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.