Skip to content

Commit 12d334f

Browse files
committed
Fix #13875 (Document and rewrite cstyleCast) [ci skip]
1 parent e4b51d7 commit 12d334f

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

man/checkers/cstyleCast.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
2+
# cstyleCast
3+
4+
Category: Type Safety
5+
Severity: Style
6+
Language: C++, not applicable for C code
7+
8+
## Motivation
9+
10+
Casts can be dangerous:
11+
* there can be unintentional loss of precision
12+
* there can be unintentional loss of sign
13+
* there can be unintentional loss of constness
14+
* there can be invalid type conversions
15+
16+
## Philosophy
17+
18+
This checker is not about readability. It is about safety.
19+
20+
We only want to warn if there are possible safety issues.
21+
22+
## Other tools / complements
23+
24+
Misra C 11.8 is violated if there is "loss of constness"
25+
26+
Misra C++ 8.2.2 is more pedantic than this checker and warns about all C style casts.
27+
28+
Warnings about "loss of constness" may be written by compilers (gcc/clang reports Wcast-qual).
29+
30+
## Example
31+
32+
### Compliant C style cast
33+
34+
The goal is to not warn about "safe" and/or "intentional" casts. For example:
35+
```
36+
int *p = (int*)0;
37+
```
38+
Replacing the C style cast with a corresponding C++ cast would not make the code safer.
39+
40+
### Non compliant
41+
42+
A cast from a base class pointer to a derived class pointer is potentially unsafe:
43+
```
44+
Derived *p = (Derived*)base;
45+
```
46+
If it can be determined that `base` points at a Derived object the cast is safe and then no warning should be reported.
47+
But otherwise a `dynamic_cast` is safer.
48+
49+
## How to fix
50+
51+
You can use the C++ casts `const_cast`, `dynamic_cast`, `reinterpret_cast`, `static_cast` to fix warnings.
52+
53+
Before:
54+
```
55+
Derived *p = (Derived*)base;
56+
```
57+
58+
After:
59+
```
60+
Derived *p = dynamic_cast<Derived*>(base);
61+
```
62+
63+
## Enable
64+
65+
--enable=style
66+

0 commit comments

Comments
 (0)