Conversion between numeric types of the same type

I read http://www.cplusplus.com/doc/tutorial/typecasting/ . It states that:

  • Otherwise, if the conversion occurs between the numeric types of the same type (integer or floating-floating), the conversion is valid, but the value is implementation-specific (and may not be portable).

But I really did not understand what the above quote means? Can someone please explain this using a simple example? Why does a conversion between a numeric type of the same type result in an implementation-specific value? What is the reason?

+5
source share
2 answers

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 do the li and i tags have the same meaning?

Answer - the values ​​depend on the number of bytes allocated for each type! That is, for some cases, int is long int , for others, long int is long long int , but in general, long er types MAY only be longer. Similar (in terms of memory size) for float , double and long double .

+5
source

This fragment means narrowing conversions between integer and floating types, respectively. That is, he argues that although conversion between integral types or between floating point types is valid, the resulting value will be determined by the implementation.

As an example, consider the following code snippet:

 #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 simple integer. However, you can convert a long long to int (i.e., the Transformation is valid), but because int cannot hold the maximum value of a long long , there cannot be an exact conversion, Thus, the value of the resulting int stays away from implementation. The same is true for conversion between long double and double .

+1
source

Source: https://habr.com/ru/post/1238802/


All Articles