Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C implicit conversions operate like they do?

When an integer number is out of the type's range, the max value + 1 is added / subtracted (depends on which part of the range the number was). For example,

unsigned short num = 65537;

num will have a value of 1 (65536 was subtracted). My question is: why does it happen? My intuition tells me it has something to do with the carry flag and the overflow flag, because the maximum value is always 1111....

Thanks in advance!

like image 699
Zakum Avatar asked Jul 15 '12 08:07

Zakum


People also ask

What is implicit conversion in C?

Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.

Why are implicit type conversions safe?

Implicit Conversions There is no special syntax for this type of conversion, this is the safest type of casting. No data is lost, for example, when converting from smaller to larger integral types or derived classes to base classes.

What happens in 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.

How is implicit conversion different from expect conversion?

In Implicit conversion, no data loss take place during the data conversion. In explicit conversion, data loss may or may not be take place during data conversion. Hence there is a risk of information loss. No possibility of throwing exception during the conversion and therefore is called type safe.


1 Answers

For a machine that uses two's-complement for signed integers the rules for conversion to an N-bit unsigned type are equivalent to discarding all but the low-order N bits. for typical hardware, this is the easiest way to do the conversion.

The standard permits other representations for signed integers, but uses the same conversion rules for the sake of consistency. This might require some extra work on such machines, but (a) such machines are quite rare, and (b) the expense should be fairly small anyway.

like image 50
Keith Thompson Avatar answered Sep 28 '22 09:09

Keith Thompson