Skip to content

Commit 8f5f3a2

Browse files
author
mikeblome
committed
fixes #1048
1 parent 28bc028 commit 8f5f3a2

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

docs/code-quality/annotating-structs-and-classes.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: Annotating Structs and Classes
3-
ms.date: 11/04/2016
3+
ms.date: 06/28/2019
44
ms.topic: "conceptual"
55
f1_keywords:
66
- "_Field_size_bytes_part_"
@@ -26,6 +26,7 @@ ms.workload:
2626
- "multiple"
2727
---
2828
# Annotating Structs and Classes
29+
2930
You can annotate struct and class members by using annotations that act like invariants—they are presumed to be true at any function call or function entry/exit that involves the enclosing structure as a parameter or a result value.
3031

3132
## Struct and Class Annotations
@@ -70,6 +71,39 @@ You can annotate struct and class members by using annotations that act like inv
7071
min(pM->nSize, sizeof(MyStruct))
7172
```
7273

74+
## Example
75+
76+
```cpp
77+
#include <sal.h>
78+
// For FIELD_OFFSET macro
79+
#include <windows.h>
80+
81+
// This _Struct_size_bytes_ is equivalent to what below _Field_size_ means.
82+
_Struct_size_bytes_(FIELD_OFFSET(MyBuffer, buffer) + bufferSize * sizeof(int))
83+
struct MyBuffer
84+
{
85+
static int MaxBufferSize;
86+
87+
_Field_z_
88+
const char* name;
89+
90+
int firstField;
91+
92+
// ... other fields
93+
94+
_Field_range_(1, MaxBufferSize)
95+
int bufferSize;
96+
_Field_size_(bufferSize) // Prefered way - easier to read and maintain.
97+
int buffer[0];
98+
};
99+
```
100+
101+
Notes for this example:
102+
103+
- `_Field_z_` is equivalent to `_Null_terminated_`. `_Field_z_` for the name field specifies that the name field is a null-terminated string.
104+
- `_Field_range_` for `bufferSize` specifies that the value of `bufferSize` should be within 1 and `MaxBufferSize` (both inclusive).
105+
- The end results of the `_Struct_size_bytes_` and `_Field_size_` annotations are equivalent. For structures or classes that have a similar layout, `_Field_size_` is easier to read and maintain, because it has fewer references and calculations than the equivalent `_Struct_size_bytes_` annotation. `_Field_size_` doesn’t require conversion to the byte size. If byte size is the only option, for example, for a void pointer field, `_Field_size_bytes_` can be used. If both `_Struct_size_bytes_` and `_Field_size_` exist, both will be available to tools. It is up to the tool what to do if the two annotations disagree.
106+
73107
## See Also
74108
75109
- [Using SAL Annotations to Reduce C/C++ Code Defects](../code-quality/using-sal-annotations-to-reduce-c-cpp-code-defects.md)

0 commit comments

Comments
 (0)