Type declaration in parentheses

I am porting an application made in c to C++ and found the following function declaration:

set_funcao(0, (double)pow((double)2, 32) );

What does the type in parentheses mean?

Is the type of return acquired at the moment, i.e. a conversion?

 6
Author: Maniero, 2019-02-10

3 answers

This is called casting, you are having the next value behave like the type that is in parentheses. In some cases it is just to instruct the compiler how to behave, in others it has a format conversion of the data and therefore some processing.

In cases of numbers the compiler already makes implicit castings when there is no data loss, in others the only way is to say that you want the casting explicitly, which is the case.

In this example the more internal casting is not necessary, if I had used 2.0 i would have done it, because this is clearly a number of type double, and it is the preferred way to do it. But since there is an implicit casting from int to double when the parameter expects a double, I could have used only 2, even without explicit casting, without anything else. The other is also not needed because the function pow() returns just one double. So I I would be suspicious of this code you picked up because it does completely unnecessary things. And I would not even use this function, why use a function for something you can do the bill in hand to get the value of 2 raised to 32 and use direct? If it were an operator the compiler would optimize and everything would be quiet, but the function will not be optimized, it is a waste. For C or c++ this usually makes a difference.

 7
Author: Maniero, 2020-08-27 17:25:21

The type in parentheses is a type casting operation (or type conversion, if you prefer).

In C++ there are different type casting operations:

Implicit conversion

This conversion happens between mutually compatible primitive types.

short a=2000;
int b;
b=a;

Explicit conversion

C++ has strong typing and so many conversions need to be explicitly declared:

short a=2000;
int b;
b = (int) a;    // notação c-like
b = int (a);    // notação funcional
 6
Author: Patrick Porto, 2019-02-10 16:23:29

Your question has already been answered, but just to supplement, in modern C++ you should avoid C - style Cast.

// Bad
int v = (int)std::pow(3, 2);

// Good
int v = static_cast<int>(std::pow(3, 2));
 0
Author: André Agenor, 2019-03-28 06:16:47