2

Possible Duplicate:
Is there any reason to use the 'auto' keyword in C / C++?

I read that:

int i;

and

auto int i;

are equivalent. If so, what's the use of auto keyword in C? Is there any special cases when auto is more useful? Or things that cant be achieved without auto??

Community
  • 1
  • 1
user1298016
  • 981
  • 1
  • 7
  • 7

2 Answers2

3

Auto is just implicit in C, but due to how rarely (read never) it is used in actual code explicitly its meaning has changed in C++11.

Auto just specifies automatic storage, meaning the variable will go away when it goes out of scope.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
1

From Wikipedia:

C (Called automatic variables.)

All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.

An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type. Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register.

Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint. In C++ the constructor of automatic variables is called when the execution reaches the place of declaration.

The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets).

This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory. See RAII.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201