Should I use static_cast every time I want to convert between primitive types?

What does this

long l = 1; char c = static_cast<char>(l); float f = 1.0f; int i = static_cast<int>(f); 

better than that

 long l = 1; char c = (char)l; float f = 1.0f; int i = (int)f; 

when transferring one primitive data type to another?

I have a lot of legacy code that uses the second style to cast types in similar situations, so this is also a question of whether I should or not perform a full-blown revision of this code.

+7
source share
5 answers

The future of proofreading.

Let's say in the future I will do this:

 float blah = 1.0f; float* f = &blah; 

Now int i = static_cast<int>(f); stops compilation, but int i = (int)f; performs reinterpret_cast .

static_cast<int> This is exactly what I want you to do. (int) does everything possible to get int. With the latter, the compiler will struggle to get the int value, and this is rarely (never?) Desirable.

+21
source

Each time it is a little indication.

You should not translate between primitive types so often that typing a few extra characters each time is an overly burdensome task. It kind of complains that you should wear a helmet every time you do some dangerous activity. If you find that the helmet is too annoying, the problem is that you too often engage in hazardous activities and not the requirements of the helmet.

Regarding addressing legacy code, you can check this question for some answers (including my own).

+8
source

Yes you should.

Castings are a major source of error. These are ways around a type system, which is one of the best error traps available to programmers.

Static_cast is much more noticeable and much more specific than the old c-style cast. You want them to stand out. You want them to be obvious when debugging. You want the next programmer to come to understand why you are doing this.

The fact that it is harder to enter static_cast<blah>(foo) is also an advantage, as it encourages you to drop only when absolutely necessary.

+6
source

Casting a constructor is an alternative. Assuming there is a conversion constructor. For example:

 int i(0); float f(3.14F); i = int(f); 

However, you should definitely static_cast for static_cast , and other C ++ will switch to C-style casting, as they basically say "try each casting until something works," which will end up in the equivalent of reinterpret_cast and probably will give you the wrong behavior.

+2
source

The problem with C-style castes is that it allows you to do conversions that you did not plan.

This is what you should do in the future, but I would not come back and change it if you did not find the problem.

+1
source

All Articles