Home > Backend Development > C++ > body text

How Does \'auto\' Determine Value vs. Reference Types in C 11?

Susan Sarandon
Release: 2024-11-04 07:53:31
Original
141 people have browsed it

How Does

Type Deduction Semantics of "auto" in C 11

In C 11, the "auto" keyword infers the type of a variable from the type of its initializer. However, determining whether "auto" resolves to a value or a reference can sometimes be ambiguous.

Value vs. Reference

The key rule for type deduction with "auto" is that the deduced type is equivalent to the declared type.

  • If the declared type is a value type, "auto" will resolve to a value.
  • If the declared type is a reference type, "auto" will resolve to a reference.

Examples

  • auto i = v.begin(); - Since v.begin() returns an iterator by value, "auto" resolves to a value.
  • const std::shared_ptr& get_foo(); - The type of the function is a reference, so "auto" will resolve to a reference.
  • static std::shared_ptr s_foo; - The type of the variable is a pointer, so "auto" will resolve to a value.
  • std::vector> c; - The type of the container is a vector of pointers, so "auto" will resolve to a value.

Type Deduction

The following example demonstrates the type deduction behavior:

<code class="cpp">int i = 5;
auto a1 = i;    // value
auto &a2 = i;  // reference</code>
Copy after login

In this example, "a1" is of type int (value), while "a2" is of type int& (reference).

Conclusion

Understanding the type deduction semantics of "auto" is crucial to write correct and efficient C code. By adhering to the rule of "auto" resolving to the declared type, developers can accurately infer variable types and leverage the benefits of this feature.

The above is the detailed content of How Does \'auto\' Determine Value vs. Reference Types in C 11?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!