Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stroustrup reason for using auto when defining a variable

Tags:

c++

c++11

I am reading Bjarne Stroustrup "The C++ programming language" book, and it is mentioned that one of the reasons for using auto in a variable definition is:

The definition is in a large scope where we want to make the type clearly visible to readers of our code.

What is the meaning of large scope here? and anyone has an example for this statement, as I feel it is not clear how using auto is making the type clearly visible to readers of the code.

like image 647
0x8F Avatar asked Apr 07 '26 06:04

0x8F


1 Answers

You took only part of the quote from the book. The entire quote is:

We use auto where we don’t have a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include:

  • The definition is in a large scope where we want to make the type clearly visible to readers of our code.
  • We want to be explicit about a variable’s range or precision (e.g., double rather than float).

The part you mentioned in the question is the Specific reason when auto should not be used, so exactly the opposite you thought.

I.e., when you want to make the type clearly visible to readers, you should not use auto.

like image 100
Andy Avatar answered Apr 09 '26 19:04

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!