Skip to content

Commit 515d5b6

Browse files
committed
Add examples explaining initialization heuristics
Adds documentation explaining that variables are considered initialized after being passed by pointer or reference to another function, thereby assuming the callee will initialize the variable. Since this may not always be desired, we also suggest using SAL annotations to more precisely describe the function behavior.
1 parent 6ad6c62 commit 515d5b6

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

docs/code-quality/c6001.md

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ To correct this warning, initialize the variable as shown in the following code:
3737
```cpp
3838
int f( bool b )
3939
{
40-
int i= -1;
40+
int i = -1;
4141
4242
if ( b )
4343
{
@@ -47,6 +47,57 @@ int f( bool b )
4747
}
4848
```
4949

50+
## Heuristics
51+
52+
Variables are also considered initialized when they are passed by reference to
53+
another function. Thus, the example below would also consider `i` to be initialized.
54+
55+
```cpp
56+
void init( int& i );
57+
58+
int f( bool b )
59+
{
60+
int i;
61+
62+
init(i);
63+
64+
if ( b )
65+
{
66+
i = 0;
67+
}
68+
return i; // i is assumed to be initialized by init(i)
69+
}
70+
```
71+
72+
This is to support the pattern of passing a pointer to a variable into an
73+
initialization function.
74+
75+
Note that many functions expect pointers to point to initialized data already,
76+
in which case this heuristic would lead to false negatives. [SAL annotations]
77+
such as `_In_` and `_Out_` can be used to more precisely describe a function's
78+
behavior. For example, in the following we call an external function that
79+
expects its argument to already be initialized and the warning is still
80+
generated.
81+
82+
```cpp
83+
void use( _In_ int& i );
84+
85+
int f( bool b )
86+
{
87+
int i;
88+
89+
use(i); // use assumes its argument is already initialized due to the _In_ annotation
90+
91+
if ( b )
92+
{
93+
i = 0;
94+
}
95+
return i; // i is uninitialized if b is false
96+
}
97+
```
98+
99+
[SAL annotations]: ./annotating-function-parameters-and-return-values.md
100+
50101
## See also
51102

52103
[Compiler Warning (level 1 and level 4) C4700](../error-messages/compiler-warnings/compiler-warning-level-1-and-level-4-c4700.md)

0 commit comments

Comments
 (0)