开发者

How do I use implicit and explicit casts? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Identify the implicit cast and explicit cast

int a = 2, b = 3开发者_如何学Go;
float f = 2.5;
double d = -1.2;

int int_result;
float real_result;

real_result = a * f;
real_result = (float) a * b;
d = a + b / a * f;
d = f * b / a + a;


If there is no loss of information the compiler will promote your data type:

int a=3;
float b=a; //b=3.0f

If there is a loss of information the compiler should demote with a warning:

float b=4.3;
int a=b;  //a=4

[

short a=2000;
int b;
b = (int) a;    // c-like cast notation
b = int (a);    // functional notation

]1


Implicit cast: real_result = a * f;

Explicit cast: real_result = (int)(a * f);


I will explain one of expression in your post:
Expression: real_result = a * f;

  1. Cast a from int -> double
  2. Calculate result of: a * f
  3. Cast result of a * f from double to int then set result to real_result

  1. Because type of real_result is int may be to small to store result of a*f (double) -> you may have a logic error in your program (loss of information).

  2. Some compilers will display a warning to notice your about logic error, if you are sure about the logic of your expression, you can tell the compiler to abort this warning by using an explicit cast:
    real_result = (int)(a * f);


int a = 2, b = 3;

float f = 2.5;

double d = -1.2;

int int_result;

float real_result;

real_result = a * f; /* Here implicit cast is applied by the compiler to variable a. Where variable a is first promoted to float implicitly and then the expression is get executed. */ real_result = (float) a * b; /* This is an explicit cast. Here you are forcibly converting the result of a*b to float. */

d = a + b / a * f;

d = f * b / a + a;

You can not implement an implicit cast. Implicit cast is implemented by the compiler.

Beware while implementing explicit cast. Because in Explicit cast the value of variable me

lost by some precision while casting big datatype value to the datatypes less than it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜