GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  Programming  >  C
Go To First  |  Previous Question  |  Next Question 
 C  |  Question 12 of 453    Print  
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));



  
Total Answers and Comments: 3 Last Update: October 09, 2007   
  
 Sponsored Links

 
 Best Rated Answer

No best answer available. Please pick the good answer available or submit your answer.
June 13, 2007 02:10:38   #1  
Priyakk Member Since: March 2007   Contribution: 3    

RE: When should a type cast be used? ...
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.

 
Is this answer useful? Yes | No
August 08, 2007 15:54:21   #2  
Prakash        

RE: When should a type cast be used? ...
Should not this example say as f (float)(i)/j; ?
 
Is this answer useful? Yes | No
October 08, 2007 23:36:30   #3  
srinivasrao        

RE: When should a type cast be used? ...
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;

 
Is this answer useful? Yes | No


 
Go To Top


 Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape