When should a type cast be used?

There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.  The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure. struct foo *p = (struct foo *) malloc(sizeof(struct foo));

Showing Answers 1 - 4 of 4 Answers

Priyakk

  • Jun 13th, 2007
 

Type casting must be done weneever the data type of the variable to which u r gonna assign some values is diff from the data type of the variable on the right side.

for instance;

float f;
int i = 10 , j = 5 ;

f = (float) ( i / j ) ;

f -------> left side variable.
i -------> right side variable.

but always make sure tht the size of the var on the left is greater than that of the right. else there will be data loss.

  Was this answer useful?  Yes

Prakash

  • Aug 8th, 2007
 

Should not this example say as f = (float)(i)/j; ?

  Was this answer useful?  Yes

srinivasrao

  • Oct 8th, 2007
 

Type cast should be used in case of if we want to assign a void pointer to a pointer of some data type.
eg:
void *ptr;
int *c;
c=(int *)ptr;

  Was this answer useful?  Yes

kbjarnason

  • Jul 2nd, 2010
 

Very, very, *VERY* rarely.  My rule of thumb is, if you see a cast, expect a design error.

One classic example of this is the oh-so-popular casting of the return value of malloc.  Don't do it.  C doesn't need it, and it can hide bugs; C++ has new, which has benefits malloc lacks.

Yes, there are cases for it, but in 20+ years of coding, I've encountered *very* few of them.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions