Is there any difference between type casting & type conversion?

前端 未结 4 920
一整个雨季
一整个雨季 2020-12-11 04:54

Is there any difference between type casting & type conversion in c++.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 05:30

    Type casting means that you take a string of bits and interpret them differently. Type conversion means that you transform a string of bits from a configuration useful in one context to a configuration useful in another.

    For example, suppose I write

    int x=65;
    char c=(char) x;
    char* s=(char*) x;
    

    c will now contain the character 'A', because if I reinterpret the decimal number 65 as a character, I get the letter 'A'. s will now be a pointer to a character string residing at memory location 65. This is almost surely a useless thing to do, as I have no idea what is at that memory location.

    itoa(x, s, 10);
    

    is a type conversion. That should give me the string "65".

    That is, with casts we are still looking at the same memory location. We are just interpreting the data there differently. With conversions we are producing new data that is derived from the old data, but it is not the same as the old data.

提交回复
热议问题