C++ auto Keyword
In this page:
Type Inference Basics
The auto keyword tells the compiler to deduce a variable's type from its initializer, rather than you spelling it out explicitly. auto x = 5; makes x an int just as if you'd written int x = 5; -- the type isn't dynamic or looser, it's determined once at compile time and fixed from then on.
Example: Type Inference Basics
#include <iostream>
int main() {
auto x = 5;
std::cout << x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
auto with Complex Types
auto can be combined with * and & to control exactly what's deduced -- auto* p requires the initializer to be a pointer, and auto& deduces a reference type, which matters when the difference between a copy and a reference changes program behavior.
Example: auto with Complex Types
#include <iostream>
int main() {
int value = 10;
auto *p = &value;
auto &ref = value;
std::cout << *p << " " << ref << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
auto with Loops
Range-based for loops are one of the most common places to see auto, since spelling out a container's full iterator or element type (like std::vector<std::pair<std::string,int>>::iterator) is often long and easy to get wrong -- for (auto& item : container) sidesteps that entirely.
Example: auto with Loops
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (auto n : nums) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
auto for Return Types
Declaring a function's return type as auto lets the compiler infer it from the return statement inside the function body, useful for template functions where the exact return type would otherwise be hard to write out or depend on the template parameters.
Example: auto for Return Types
#include <iostream>
auto add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
auto with Lambdas
Lambda expressions are usually stored in auto-declared variables since a lambda's actual type is a compiler-generated, unnameable closure type -- you literally cannot write out its type by hand. auto is also used for generic lambda parameters ([](auto x, auto y)), letting one lambda accept multiple argument types.
Example: auto with Lambdas
#include <iostream>
int main() {
auto square = [](int x) { return x * x; };
std::cout << square(5) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: