Ethical Hacking Programming, Blogging, Hosting, All Computer Software, PC Software Download, JAVA in hindi, HTML, PHP, C, C++, Free Learning, Software's Download, Technical Videos, Technical Tricks and Tips, How Make Money

Relational and Logical Operations C programming class 12

2.11 Type Conversions and Casts


When an operator has operands of di erent types, they are converted to a common type according to a small number of rules [KR88, page 42].

For a binary expression such as a * b, the following rules are followed (assuming neither operand is unsigned):

If either operand is long double, convert the other to long double.

Otherwise, if either operand is double, convert the other to double.

Otherwise, if either operand is float, convert the other to float.

Otherwise, change all four and intensely short and, if any circuit is long, then change the other for a long time

If the two operands consist of a signed and an unsigned version of the same type, then the signed operand will be promoted to unsigned, with strange results if the previously signed value was negative.

A simple example of type promotion is shown in the following code.

short a = 5;

int b = 10;

float c = 23.1f;

double d = c + a*b;

Here the multiply is performed first, so a is promoted to int and multiplied with b. The integer result of this expression is promoted to float and added to c. This result is then promoted to double and assigned to d.


Note. The promotion from char to int is implementation-dependent, since whether a plain char is signed or unsigned depends on the compiler. Some platforms will perform “sign extension” if the left-most bit is 1, while others will fill the high-order bits with zeros—so the value is always positive.

Assignment to a “narrower” operand is possible, although information may be lost. Conversion to a narrower type should elicit a warning from good compilers. Conversion from a larger integer to a smaller one results in truncation of the higher-order bits, and conversion from floating-point to integer causes truncation of any fractional part. For example,

int iresult = 0.5 + 3/5.0;

The division 3/5.0 is promoted to type double so that the final summation equals 1.1. The result then is truncated to 1 in the assignment to iresult. Note, a conversion from double to float is implementation dependent and might be either truncated or rounded.

Narrowing conversions should be avoided. For the cases where they are necessary, they should be made explicit by a cast. For example,

int iresult = (int)(0.5 + 3/5.0);

Casts can also be used to coerce a conversion, such as going against the promotion rules specified above. For example, the expression

result = (float)5.0 + 3.f;

will add the two terms as float’s rather than double’s.

Share:

No comments:

Post a Comment

Follow On YouTube