We know that a double
literal value won't be implicitly converted to float
due to data loss at compile time:
We also know that int
won't be implicitly converted to byte
as well, but in this case, taking into account the literal is int
, it works:
Would you mind explaining me what's the process happening there and how it works under the hood?
For example, the compiler implicitly converts any pointer to int into a pointer to const int where necessary.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
Type Conversion in C++ Implicit Type Conversion Also known as 'automatic type conversion'. Done by the compiler on its own, without any external trigger from the user.
A literal integer is a constant, it will never change. The compiler can therefore reason out at compile time if the implicit conversion is safe and if it is, its nice enough to do it for you.
Thats also the reason why byte i = 300;
will fail at compile time.
The same can’t be said when the conversion is of a non constant value; a variable. There is no way the compiler can know what value i
will be so the implicit conversion is unsafe and disallowed.
Concerning why this behavior seems off with floats and doubles (see comments): The reason is that there is a float literal in the language, so if you want a float literal, use a float literal. There is no byte or short literal so the compiler helps you out
Also, fitting a valid int
into a byte
implies no loss of data/precision; the bits are the same, you are simply truncating 0 bits on the high end. The same can't be said when you convert a double
into a float
. The representation of any given number as a single or double precision floating point number are radically different and there is an inherent loss of precision. It stands to reason that the language design decisions differ between both scenarios as they are different alltogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With