Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of "auto" keyword in c

Tags:

c

keyword

Could you please give me the exact concept of the keyword auto in a C program.

When I went through the book Deep C secrets, I saw this quote:

The auto keyword is apparently useless. It is only 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 global static allocation, or dynamic allocation on the heap). Auto is irrelevant to other programmers, since you get it by default.

like image 688
Renjith G Avatar asked Jan 14 '11 07:01

Renjith G


People also ask

What is auto keyword in C?

Auto is a storage class/ keyword in C Programming language which is used to declare a local variable. A local variable is a variable which is accessed only within a function, memory is allocated to the variable automatically on entering the function and is freed on leaving the function.

What is auto keyword in C with example?

The auto keyword declares automatic variables. For example: auto int var1; This statement suggests that var1 is a variable of storage class auto and type int. Variables declared within function bodies are automatic by default.

What is the use of keyword auto?

The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.

Is Auto a reserved keyword in C?

There are 32 reserved keywords that are used in C programming. Below are the 32 reserved keywords and their functions. 1. Auto- This keyword is used for automatic variables.


2 Answers

auto isn't a datatype. It's a storage class specifier, like static. It's basically the opposite of static when used on local variables and indicates that the variable's lifetime is equal to its scope (for example: when it goes out of scope it is automatically destroyed).

You never need to specify auto as the only places you're allowed to use it it is also the default.

like image 128
Laurence Gonsalves Avatar answered Nov 15 '22 09:11

Laurence Gonsalves


It might be useful in C89 where you have an implicit int rule.

void f() {
  a = 0; // syntax error
  auto b = 0; // valid: parsed as declaration of b as an int
}

But then, you can just write straight int instead of auto. C99 doesn't have an implicit int rule anymore. So I don't think auto has any real purpose anymore. It's "just the default" storage specifier.

like image 33
Johannes Schaub - litb Avatar answered Nov 15 '22 09:11

Johannes Schaub - litb