Skip to content

Commit cb76e52

Browse files
authored
Partial fix #14227 (Add checker documentation for truncLongCastAssignment and truncLongCastReturn) [skip ci] (danmar#7979)
1 parent 602da94 commit cb76e52

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

man/checkers/truncLongCast.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# truncLongCastAssignment and truncLongCastReturn
2+
3+
**Message**: int result is assigned to long variable. If the variable is long to avoid loss of information, then you have loss of information.<br/>
4+
**Category**: Type Safety<br/>
5+
**Severity**: Style<br/>
6+
**Language**: C/C++
7+
8+
## Description
9+
10+
This checker warns when a calculation has type 'int' and it could potentially overflow that and the result is implicitly or explicitly converted to a larger
11+
integer type after the loss of information has already occured.
12+
13+
## Motivation
14+
15+
The motivation of this checker is to catch bugs. Unintentional loss of information.
16+
17+
## How to fix
18+
19+
You can fix these warnings by:
20+
1. Add explicit cast to avoid loss of information
21+
2. Explicitly truncate the result
22+
3. Change type of assigned variable
23+
24+
Before:
25+
```cpp
26+
void foo(int32_t y) {
27+
int64_t x = y * y; // <- warning
28+
}
29+
```
30+
31+
After (explicit cast):
32+
```cpp
33+
void foo(int32_t y) {
34+
int64_t x = (int64_t)y * y; // <- 64-bit multiplication
35+
}
36+
```
37+
38+
After (explicitly truncate the result):
39+
```cpp
40+
void foo(int32_t y) {
41+
int64_t x = (int32_t)(y * y); // redundant cast makes it explicit that your intention is to truncate the result to 32-bit
42+
}
43+
```
44+
45+
After (change type of assigned variable):
46+
```cpp
47+
void foo(int32_t y) {
48+
int32_t x = y * y;
49+
}
50+
```

0 commit comments

Comments
 (0)