Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool for finding C-style Casts

Tags:

c++

c

Does anyone know of a tool that I can use to find explicit C-style casts in code? I am refactoring some C++ code and want to replace C-style casts where ever possible.

An example C-style cast would be:

Foo foo = (Foo) bar; 

In contrast examples of C++ style casts would be:

Foo foo = static_cast<Foo>(bar); Foo foo = reinterpret_cast<Foo>(bar); Foo foo = const_cast<Foo>(bar); 
like image 374
waffleman Avatar asked Apr 07 '10 14:04

waffleman


People also ask

Can I use Static_cast in C?

Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.

What is a C-style cast?

C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.

When should I use Reinterpret_cast?

Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.

How do you cast in C++?

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.


2 Answers

If you're using gcc/g++, just enable a warning for C-style casts:

g++ -Wold-style-cast ... 
like image 102
jonner Avatar answered Oct 05 '22 17:10

jonner


Searching for the regular expression \)\w gives surprisingly good results.

like image 32
sth Avatar answered Oct 05 '22 18:10

sth