views:

633

answers:

4

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

A: 

One of the major differences occurs when you work with strings. You cannot say (int)"234" and get the integer 234. Type casting generally only works on primitive numeric data types.

John Smith
+10  A: 

Generally, casting refers to an explicit conversion, whether it's done by C-style cast (T(v) or (T)v) or C++-style cast (static_cast, const_cast, dynamic_cast, or reinterpret_cast). Conversion is generally a more generic term used for any time a variable is converted to another:

std::string s = "foo"; // Conversion from char[] to char* to std::string
int i = 4.3; // Conversion from float to int
float *f = reinterpret_cast<float*>(&i); // (illegal) conversion from int* to float*
coppro
so there is no difference right
Passionate programmer
The difference is that a cast is *explicit*. The C++ keywords can be grep'ed. Both the C and C++ cast show that the conversion was done on purpose and with the consent of the programmer. An implicit conversion could be intended, or by mistake.
DevSolar
A: 

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 not we 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.

Jay
A: 

While we are reading an integer

int i=parseInt.Integer(readLine(str));

Here we are entering a value, the JVM consider that as string after that it will be converted to Int. This is called as Type casting.

float f=7.9; int i=(int)f; Here we are casting the float value to integer value. this is called Type Casting.

Krishna