PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] How does the auto keyword deduct the type in C++

 July 09, 2022     c++, keyword, types, variables     No comments   

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 autokeyword 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing