Issue
I wonder how the auto keyword determines the type of a variable in c++. I thought that statically typed languages couldn't do that. For example, how does this work:
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
auto a = 5433245244524;
std::cout << a << std::endl;
}
Solution
It works in same way as deduction of expression returning type for templates. It happens at compilation type, so it is a static type.
Literal 5433245244524
comprises initializing expression. You can get the type of expression at compile time (static type) by using operator decltype()
. E.g.
decltype(5433245244524) a = 5433245244524;
But auto
keyword is more than that. It's a placeholder type. E.g. in statement
const auto& a = 5433245244524;
Here auto
replaces identifier of type without qualifiers to form a compatible reference type.
There is a number of other uses for keyword auto
, e.g. function's trailing return type, etc. see https://en.cppreference.com/w/cpp/language/auto
Answered By - Swift - Friday Pie Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.