Skip to content

Commit fefd48b

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

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

man/checkers/cstyleCast.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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. For example:
36+
```
37+
int *p = (int*)0;
38+
```
39+
Replacing the C style cast with a corresponding C++ cast would not make the code safer.
40+
41+
### Non compliant C style cast
42+
43+
A cast from a base class pointer to a derived class pointer is potentially unsafe:
44+
```
45+
Derived *p = (Derived*)base;
46+
```
47+
If it is obvious that `base` always point at a Derived object the cast is safe and ideally no warning should be reported.
48+
But otherwise a `dynamic_cast` is safer.
49+
50+
## How to fix
51+
52+
You can use `dynamic_cast` or `static_cast` to fix warnings.
53+
54+
Before:
55+
```
56+
Derived *p = (Derived*)base;
57+
```
58+
59+
After:
60+
```
61+
Derived *p = dynamic_cast<Derived*>(base);
62+
```
63+
64+
## Enable
65+
66+
--enable=style
67+

0 commit comments

Comments
 (0)