Destructor
Destructor

Reputation: 14458

Conversion between numeric types of the same kind

I was reading http://www.cplusplus.com/doc/tutorial/typecasting/. It says that:

But I really didn't understand what does the above quote mean to say? Will someone please explain it using an simple example? Why conversion between numeric type of same kind results in implementation-specific value? What is the reason?

Upvotes: 5

Views: 207

Answers (2)

VolAnd
VolAnd

Reputation: 6407

Let's consider the following example:

    long long int lli = 5000000000;
    long int li;
    int i;
    li = lli;
    i = li;

Can you predict the values of lli, li and i? Or whether li and i have the same value?

Answer is - values depend on the number of bytes allocated for each type! I.e. for some cases int is equal to long int, for others long int is equal to long long int, but in general longer types just CAN be longer. Similar (in sense of memory size) for float, double and long double.

Upvotes: 5

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42939

The snippet refers to narrowing conversions between integral and floating point types respectively. That is, it states that although a conversion between integral types or between floating point types is valid, the resulting value will be implementation defined.

As an example consider the following piece of code:

#include <iostream>
#include <limits>

int main() {
  long long lgm = std::numeric_limits<long long>::max();
  std::cout << std::hex << lgm << std::endl;
  int i = lgm;
  std::cout << std::hex << i << std::endl;

  long double ldb = std::numeric_limits<long double>::max();
  std::cout << std::hex << ldb << std::endl;
  double db = ldb;
  std::cout << std::hex << db << std::endl;
}

Output:

7fffffffffffffff
ffffffff
1.18973e+4932
inf

As you can see the maximum value of long long integer exceeds the capacity of a plain integer. However you can convert a long long to an int (i.e., the conversion is valid), but due to the fact that the int can't hold the maximum value of a long long there cannot be an accurate conversion. Thus, the value of the resulting int is left to be decided by the implementation. The same holds true for the conversion between long double and double.

Upvotes: 1

Related Questions