One of the most iconic C++ features is the language’s ability to deduce types with the auto keyword. In this post, I’ll give a series of code snippits. Your job is to assess what will be deduced for v in each case. Determine for each:The deduced typeIf it is a value, an lvalue or rvalue reference, or a pointerWhich CV qualifiers are applicableSome of these may not even compile, so “this won’t work” is a totally valid answer.Each section increases in difficulty. Good luck!Enter the Gauntlet#Basics#Basic assignments and deduction from constants and straightforward types. auto v = 5; AnswerType: intExplanation: Straightforward type deduction from an integer constant. auto v = 0.1; AnswerType: doubleExplanation: Notably different than integers. Floating points default to the larger double instead of float. int x; auto v = x; AnswerType: intExplanation: Simple type derived from the assigned-from variable. auto v = 5, w = 0.1; AnswerType: Fails to compile.Explanation: All types in an expression defined with auto have to be the same. int x; auto v = &x; AnswerType: int*Explanation: Auto will deduce pointers. auto v = nullptr; AnswerType: std::nullptr_tExplanation: nullptr has its own type. auto v = { 1, 2, 3 }; AnswerType: std::initializer_list<int>Explanation: It might seem like this should create a container, but it won’t! int x[5]; auto v = x; AnswerType: int*Explanation: C-style arrays decay to a pointer. The decay happens before auto is evaluated. int foo(int x) { return x; } auto v = foo; AnswerType: int (*) (int)Explanation: auto can deduce function pointers.Exploring how references and CV-qualifiers are handled. volatile const int x = 1; auto v = x; AnswerType: intExplanation: auto drops top-level CV qualifiers. volatile const int x = 1; auto v = &x; AnswerType: volatile const int*Explanation: CV qualifiers applied to pointed-to or referred-to types are maintained. int x; int& y = x; auto v = y; AnswerType: intExplanation: auto will never deduce a reference on its ...
First seen: 2025-12-15 05:56
Last seen: 2025-12-15 17:58