File: dangerousTypeCast.md

package info (click to toggle)
cppcheck 2.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,132 kB
  • sloc: cpp: 268,935; python: 20,890; ansic: 8,090; sh: 1,045; makefile: 1,008; xml: 1,005; cs: 291
file content (43 lines) | stat: -rw-r--r-- 909 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# dangerousTypeCast

**Message**: Potentially invalid type conversion in old-style C cast, clarify/fix with C++ cast<br/>
**Category**: Type Safety<br/>
**Severity**: Warning<br/>
**Language**: C++, not applicable for C code

## Motivation

C style casts can be dangerous in many ways:
 * loss of precision
 * loss of sign
 * loss of constness
 * invalid type conversion

## Philosophy

This checker warns about old style C casts that perform type conversions that can be invalid.

This checker is not about readability. It is about safety.

## How to fix

You can use `dynamic_cast` or `static_cast` to fix these warnings.

Before:
```cpp
struct Base{};
struct Derived: public Base {};
void foo(Base* base) {
    Derived *p = (Derived*)base; // <- can be invalid
}
```

After:
```cpp
struct Base{};
struct Derived: public Base {};
void foo(Base* base) {
    Derived *p = dynamic_cast<Derived*>(base);
}
```