diff --git a/docs/project/cpp_style_guide.md b/docs/project/cpp_style_guide.md index 02a9088f223b..4d48df04fb8d 100644 --- a/docs/project/cpp_style_guide.md +++ b/docs/project/cpp_style_guide.md @@ -16,6 +16,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - [General naming rules](#general-naming-rules) - [File names](#file-names) - [Syntax and formatting](#syntax-and-formatting) + - [Naming variable types and the use of `auto`](#naming-variable-types-and-the-use-of-auto) - [Copyable and movable types](#copyable-and-movable-types) - [Static and global variables](#static-and-global-variables) - [Foundational libraries and data types](#foundational-libraries-and-data-types) @@ -197,6 +198,22 @@ these. `protected`. This is motivated by the `misc-non-private-member-variables-in-classes` tidy check. +### Naming variable types and the use of `auto` + +We generally use `auto` for most local variables when a type can be inferred, +except for primitive types such as `bool` and `int`. It is not required to use +`auto`, and shorter type names such as `SemIR::InstId` are sometimes named even +though they could be inferred. Naming the type can be helpful in cases where the +type would be obscure and can not be explained with the variable name. Function +parameters generally name the type of each parameter, though lambdas may use +`auto` if it's helpful. + +When naming variables, we typically suffix `_id` for ID types. When needed, we +can also resolve ambiguity by referring to the full type name in the variable +name; for example, if there's a `ClassId`, `InstId`, and `TypeId` for the same +class entity, we might call these `class_id`, `class_inst_id`, and +`class_type_id`. Similarly, we might call an `Inst` `class_inst`. + ### Copyable and movable types - Types should have value semantics and support both move and copy where