I have a code which goes like :
int main(void)
{
char mychar = 'd';
int *ptr = malloc(sizeof(*ptr)) ;
*ptr = (char) 'c' ; // *ptr = (char*) 'c'; Gives the exact same result
printf("%c\n",*ptr);
memset(ptr,mychar,sizeof(*ptr));
printf("%c\n",*ptr);
free(ptr);
printf("%c\n",*ptr);
return 0 ;
}
The code gives the same result for pointer style cast and datatype cast.
Which among the two styles should be used or is considered a good practice and why ?
*ptr = (char) 'c' ;
*ptr = (char*) 'c';
Neither.
Both
*ptrand'c'are of typeint. No cast is necessary.(Yes, character constants in C are of type
int, notchar. This is counterintuitive, but there are historical reasons for it. Note that C++ character constants are of typechar.)The cast in
*ptr = (char) 'c';is relatively harmless; it converts theintvalue of'c'tochar, and the result is implicitly converted back toint. Sincecis guaranteed to be representable as achar, it’s not going to cause an error.In
*ptr = (char*) 'c';, your compiler should give you an error message. You’re converting a constantintvalue to a pointer, and then assigning that pointer value to anintwithout a cast. This is a “constraint violation”, which means that a conforming compiler must diagnose it. If yours doesn’t, find out how to make it do so.If the assignment gets past the compiler, it might do what you want. Conversions between integer types and pointer types typically just reinterpret the bits that name up the representation, so converting an
intto achar*and back to anintis likely to give you the originalintvalue. But it’s not guaranteed.Casts are usually unnecessary even between different arithmetic types. For example, if you had written:
In this case, the right side of the assignment really is of type
char, because it’s the name of an object of that type, not a character constant. The assignment implicitly converts the value ofchfrom typecharto typeint. You could write:instead, but that just specifies the same conversion that would have been done without the cast. And it’s error-prone; it introduces the opportunity to get the type wrong, as opposed to letting the compiler handle it for you.
Casts in general should be viewed with suspicion.