- Examples
Examples for using the auto keyword in different cases.
We'll cover the following...
Example 1
Press + to interact
// auto.cpp#include <iostream>#include <vector>int func(int){return 2011;}int main(){auto i = 5; // intauto& intRef = i; // int&auto* intPoint = &i; // int*const auto constInt = i; // const intstatic auto staticInt = 10; // static intstd::vector<int> myVec;auto vec = myVec; // std::vector<int>auto& vecRef = vec; // std::vector<int>&int myData[10];auto v1 = myData; // int*auto& v2 = myData; // int (&)[10]auto myFunc = func; // (int)(*)(int)auto& myFuncRef = func; // (int)(&)(int)// define a function pointerint (*myAdd1)(int, int) = [] (int a, int b){return a + b;};// use type inference of the C++11 compilerauto myAdd2 = [](int a, int b){return a + b;};std::cout << "\n";// use the function pointerstd::cout << "myAdd1(1, 2) = " << myAdd1(1, 2) << std::endl;// use the auto variablestd::cout << "myAdd2(1, 2) = " << myAdd2(1, 2) << std::endl;std::cout << "\n";}
Explanation
In the example above, the complier automatically deduces the types depending on the value stored in ...
Access this course and 1400+ top-rated courses and projects.