Skip to content

Commit 4a96799

Browse files
authored
Document our practices around using auto and naming variable types (#5663)
We use `auto` for most local variables, and we put the type name into the variable name in common cases, especially for our ID types. This was discussed in `#style`: https://discord.com/channels/655572317891461132/821113559755784242/1380091326900469801
1 parent 64ad57a commit 4a96799

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

docs/project/cpp_style_guide.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
1616
- [General naming rules](#general-naming-rules)
1717
- [File names](#file-names)
1818
- [Syntax and formatting](#syntax-and-formatting)
19+
- [Naming variable types and the use of `auto`](#naming-variable-types-and-the-use-of-auto)
1920
- [Copyable and movable types](#copyable-and-movable-types)
2021
- [Static and global variables](#static-and-global-variables)
2122
- [Foundational libraries and data types](#foundational-libraries-and-data-types)
@@ -197,6 +198,22 @@ these.
197198
`protected`. This is motivated by the
198199
`misc-non-private-member-variables-in-classes` tidy check.
199200
201+
### Naming variable types and the use of `auto`
202+
203+
We generally use `auto` for most local variables when a type can be inferred,
204+
except for primitive types such as `bool` and `int`. It is not required to use
205+
`auto`, and shorter type names such as `SemIR::InstId` are sometimes named even
206+
though they could be inferred. Naming the type can be helpful in cases where the
207+
type would be obscure and can not be explained with the variable name. Function
208+
parameters generally name the type of each parameter, though lambdas may use
209+
`auto` if it's helpful.
210+
211+
When naming variables, we typically suffix `_id` for ID types. When needed, we
212+
can also resolve ambiguity by referring to the full type name in the variable
213+
name; for example, if there's a `ClassId`, `InstId`, and `TypeId` for the same
214+
class entity, we might call these `class_id`, `class_inst_id`, and
215+
`class_type_id`. Similarly, we might call an `Inst` `class_inst`.
216+
200217
### Copyable and movable types
201218
202219
- Types should have value semantics and support both move and copy where

0 commit comments

Comments
 (0)