Type declaration in parentheses

Asked

Viewed 144 times

6

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

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

What does the type in parentheses mean?

It is the type of return acquired at the time, ie a conversion?

3 answers

7


That’s called casting, you are sending the next value to behave as the type that is in parentheses. In some cases it is only to instruct the compiler of how to behave, in others it has a format conversion of the data and therefore some processing.

In cases of numbers the compiler already does casting implicit 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 casting more internal is not necessary if you had used 2.0 was the same, because this is clearly a number double, and is the preferred way to do it. But as there is a casting implicit of int for double when the parameter expects a double, could have just used 2, even without casting explicit, without anything else. The other is also not necessary because the function pow() just returns a double. So I would distrust this code that you took because it does completely unnecessary things. And I wouldn’t even use this function, so why use a function for something that you can do at hand to get the value of 2 to the 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.

  • Thank you she reply. This code is from a very old Free Software program made in C. I’m studying C++ trying to migrate it, according to Bjarne’s Book.

  • If you want to learn C++ learn C++, don’t use any C, they are completely different languages.

6

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

In C++ there are different casting operations of types:

Implicit conversion

This conversion happens between primitive types compatible with each other.

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

Explicit conversion

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

short a=2000;
int b;
b = (int) a;    // notação c-like
b = int (a);    // notação funcional
  • Thank you for your reply. . :)

0

Your question has already been answered, but just to complement, 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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.