Skip to content

Commit 4fcbdc3

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

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

man/checkers/cstyleCast.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
2+
# cstyleCast
3+
4+
**Category**: Type Safety<br/>
5+
**Severity**: Style<br/>
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 warns about old style C casts.
19+
20+
This checker is not about readability. It is about safety.
21+
22+
We only want to warn if there are possible safety issues and a C++ cast can provide better safety.
23+
24+
## Other tools / complements
25+
26+
Related checkers:
27+
* Misra C 11.8 is violated if there is "loss of constness"
28+
* Misra C++ 8.2.2 is more pedantic than this checker and warns about all C style casts.
29+
* Warnings about "loss of constness" may be written by compilers (gcc/clang reports Wcast-qual).
30+
31+
## Example
32+
33+
### Compliant C style cast
34+
35+
The goal is to not warn about "safe" and/or "intentional" casts.
36+
37+
For example:
38+
```
39+
int *p = (int*)0;
40+
```
41+
42+
### Non compliant C style cast
43+
44+
A cast from a base class pointer to a derived class pointer is potentially unsafe:
45+
```
46+
Derived *p = (Derived*)base;
47+
```
48+
If it is obvious that `base` always point at a Derived object the cast is safe and ideally no warning should be reported.
49+
But otherwise a `dynamic_cast` is safer.
50+
51+
## How to fix
52+
53+
You can use `dynamic_cast` or `static_cast` to fix warnings.
54+
55+
Before:
56+
```
57+
Derived *p = (Derived*)base;
58+
```
59+
60+
After:
61+
```
62+
Derived *p = dynamic_cast<Derived*>(base);
63+
```
64+
65+
## Enable
66+
67+
--enable=style
68+

0 commit comments

Comments
 (0)