Here is a MWE of something I came across in some C++ code.
int a = (int)(b/c);
Why is (int)
after the assignment operator?
Is it not recommended to use it like this?
Here is a MWE of something I came across in some C++ code.
int a = (int)(b/c);
Why is (int)
after the assignment operator?
Is it not recommended to use it like this?
This is simply a C-style typecast. It is used to make the author's intentions explicit, especially when the result of b/c
is of another type (such as unsigned
or float
).
Without the cast, you will often get a compiler warning about an implicit conversion which can sometimes have consequences. By using the explicit cast, you are stating that you accept this conversion is fine within whatever other limits your program enforces, and the compiler will perform the conversion without emitting a warning.
In C++, we use static_cast<int>(b/c)
to make the cast even more explicit and intentional.
This is a cast used to convert a variable or expression to a given type. In this case if b
and c
were floating point numbers, adding the cast (int)
forces the result to an integer.
Specifically this is a "C style cast", modern C++ has some additional casts to given even more control (static_cast, dynamic_cast, const_cast etc)
It is not "(int) after the assignment operator".
It is "(int) before a float - the result of b/c".
It casts the float to an int.
This is a mistake. In the code:
int a = b/c;
then it may cause undefined behaviour if the result of the division is a floating point value that is out of range of int
(e.g. it exceeds INT_MAX
after truncation). Compilers may warn about this if you use warning flags.
Changing the code to int a = (int)(b/c);
has no effect on the behaviour of the code, but it may cause the compiler to suppress the warning (compilers sometimes treat a cast as the programmer expressing the intent that they do not want to see the warning).
So now you just have silent undefined behaviour, unless the previous code is designed in such a way that the division result can never be out of range.
A better solution to the problem would be:
long a = std::lrint(b/c);
If the quotient is out of range then this will store an unspecified value in a
and you can detect the error using floating point error handling. Reference for std::lrint