
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Does an Auto Keyword Do in C++
The auto keyword in C++ is used to automatically determine the type of variables from their initializer. This means you don't need to explicitly tell the compiler the variable's data type. It lets the compiler determine the variable's type during compile time.
C++ auto Keyword
Auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used. All this changed with the introduction of auto to do type deduction from the context in C++11. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after a new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself.
With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program.
The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.
Syntax
Here is the following syntax for the auto keyword in C++:
auto variable_name = value;
Example of auto Keyword
In the following code, we can see how the auto keyword has automatically deduced the type of variable and executed the program:
#include <iostream> using namespace std; int main() { // Using auto to detect the type of the variable auto x = 10; // int auto y = 3.14; // double auto name = "Aman"; // const char* cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "name = " << name << endl; return 0; }
Here is the output of the above example:
x = 10 y = 3.14 name = Aman
Use of auto with STL
The auto keywords is helpful when working with the standard template Library containers, like vector, map, set, etc, which often use complex types (like iterators), and using auto makes the code cleaner and automatically deduces those types.
Example
Here is an example of auto keyword using with C++ STL vector:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v = {1, 2, 3}; // Using auto, which automatically deduces the iterator's type for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << " "; } /* Without auto: for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) { cout << *it << " "; } */ return 0; }
Here is the output of the above example:
1 2 3