✨ C++ auto Keyword – Let C++ Guess the Type for You
Don’t feel like typing long data types like std::vector<int>::iterator? Good news! The auto keyword lets C++ do the guessing for you! 🧠
When you use auto, the compiler figures out the variable’s type based on the value you assign to it.
🛠️ Syntax
auto variableName = value;
🔧 Example: Let the Compiler Do the Work
#include <iostream>
using namespace std;
int main() {
auto x = 10; // int
auto y = 3.14; // double
auto z = "Hello"; // const char*
cout << x << ", " << y << ", " << z << endl;
return 0;
}
🧪 When is auto Useful?
- When the type is super long or hard to write
- When working with STL containers (like
map,vector) - To improve code readability and reduce errors
💡 Caution!
autoonly works when you initialize the variable.- Sometimes the guessed type might not be what you expected. 🧐
🧠 Simple Tip to Remember
One word instead of many: Use auto when the compiler already knows what you mean!