Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion at compile time

Tags:

c#

.net

We know that a double literal value won't be implicitly converted to float due to data loss at compile time:

enter image description here

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:

enter image description here

Would you mind explaining me what's the process happening there and how it works under the hood?

like image 685
Maxim Zhukov Avatar asked Oct 18 '18 09:10

Maxim Zhukov


People also ask

Which of the following conversion is carried out implicitly by the compiler?

For example, the compiler implicitly converts any pointer to int into a pointer to const int where necessary.

What is an implicit conversion?

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.

What is implicit conversion in SQL Server?

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.

Which of the following types of conversions is implicit in C++?

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.


1 Answers

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.

like image 123
InBetween Avatar answered Oct 06 '22 01:10

InBetween