Identify the implicit cast and explicit cast [clos

2020-05-11 09:37发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

I would appreciate it if anyone can answer my question.
Identify the implicit cast and explicit cast?

int a = 2, b = 3;

float f = 2.5;
double d = -1.2;
int int_result;
float real_result;

回答1:

Formally, the question makes no sense from the terminological point of view. There's no such thing as "implicit cast". The whole point of the term cast is that it designates an explicitly-requested conversion. Cast is the type conversion explicitly requested by the operator of the (type) form.

What in this case can be explicit or implicit is called conversion. This is what was probably meant by the author of the question, but screwed up by their poor knowledge of C terminology.

In your code sample only one initialization requires a conversion. And, of course, that conversion is implicit, since there are no casts in your code whatsoever.



回答2:

By definition, casts are always explicit. What is implicit is conversion. When an object is assigned a value that is not the type of the object, then one of the two things can happen:

  1. the type of the value is "compatible" with the type of the object, i.e., the standard allows such an assignment. Then, the compiler does a conversion for you. This is called implicit conversion. For example, size_t i = -1; has an implicit conversion of the int −1 to size_t.
  2. otherwise, the compiler must issue a diagnostic in this case, and you need a cast to do the assignment. The result of such a cast is either implementation-defined or undefined.

Given the above, you rarely need casts in C. One of the times you need a cast might be in a variadic function because the compiler cannot do the implicit conversion for you. Another example would be to convert an integer to a pointer in an implementation-defined way.

Once more, there is no such thing as implicit cast.



回答3:

well, this is actually a home work in C class, and there was an example answer given for the first line wirtten in the above, which i didnt undersand:which was,

int_result = a * f;
// a is casted implicitly to float by the multiplication operation a*f,
// the product is then casted implicitly to int by the = (assignment) operation.
real_result = a * f;
real_result = (float) a * b;
d = a + b / a * f;
d = f * b / a + a;

thanks again, look forward your replies!! :)



回答4:

int a = 2, b = 3;

float f = 2.5;

double d = -1.2; //This is an implicit cast.

int int_result;

float real_result;

There is no explicit cast in above statements.