to cast or not to cast? 
Author Message
 to cast or not to cast?

When, and when not, should one cast a pointer?  For instance...  I have
had someone tell me that casting a pointer from malloc() is of bad
style.  Conversely, I have also had someone tell me that not casting a
pointer from malloc() is bad style.  Without getting into reglious and
preference issues, when and when should someone *not* cast a pointer?

Sent via Deja.com http://www.*-*-*.com/
Before you buy.



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> When, and when not, should one cast a pointer?

Only cast pointers when it is necessary.  This is relatively
rare in simple code, sometimes more common in complex data
structures.

Quote:
> For instance...  I have
> had someone tell me that casting a pointer from malloc() is of bad
> style.

Because it is unnecessary.

Quote:
> Conversely, I have also had someone tell me that not casting a
> pointer from malloc() is bad style.

He is wrong.

Quote:
> Without getting into reglious and preference issues, when and
> when should someone *not* cast a pointer?

--
"I should killfile you where you stand, worthless human." --Kaz


Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> When, and when not, should one cast a pointer?  For instance...  I have
> had someone tell me that casting a pointer from malloc() is of bad
> style.  Conversely, I have also had someone tell me that not casting a
> pointer from malloc() is bad style.  Without getting into reglious and
> preference issues, when and when should someone *not* cast a pointer?

> Sent via Deja.com http://www.deja.com/
> Before you buy.

NEVER cast the return value from malloc in C. There are other
considerations in other languages but we're talking C only here.
malloc/calloc/realloc return a pointer to void and therefore can
represent a pointer to any C type (other than a function pointer) and
may be assigned to such a type without the need for a cast. By including
stdlib.h your compiler will "see" the proper prototypes for this family
of functions and will therefore know what to do. Here's a real life
gotcha...

1. Forget to include stdlib.h
2. Cast the return value from malloc
3. Try this on a 64-bit Alpha
4. Start looking for another job.

Why? Because, in the absence of a prototype for malloc, the compiler
will assume that it returns int. By applying a cast, you are telling the
compiler that you know what you're doing. On your 64-bit system, the
compiler will therefore be misled into believing that malloc returns int
and will apply certain conversions to the value that it gets in the
return register before assigning it to your target pointer variable. The
net effect is that the most significant 32 bits of the value that was
actually returned from malloc, may be masked off.



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

>When, and when not, should one cast a pointer?

Only use an explicit cast when you have to.  The explicit cast is an
indication to the compiler saying, "What I'm doing here may look a bit
iffy but trust me.  Do the conversion and don't fuss."  If you're doing
this a lot in your code there's something wrong.

There's one case where an explicit cast does something slightly
different - when you're passing a parameter to a function which
takes a variable number of parameters and you want to ensure that
the actual thing passed is of the correct type.

Quote:
>For instance...  I have
>had someone tell me that casting a pointer from malloc() is of bad
>style.

This is a particular case of the general rule, "Don't cast where it
isn't necessary".  malloc returns a "void *" and this will be converted
to whatever pointer type you have correctly without needing an explicit
cast.  Adding the explicit cast buys you nothing and can hide errors -
specifically a failure to #include stdlib.h.

Quote:
>Conversely, I have also had someone tell me that not casting a
>pointer from malloc() is bad style.

They may have been referring to C++.  In C++ the rules for void *
are different and the cast is necessary.  OTOH, using malloc at
all in C++ can be considered bad style.

Quote:
>Without getting into reglious and
>preference issues, when and when should someone *not* cast a pointer?

Never when it isn't necessary.  (And if your code contains a lot of
casts there's something wrong.)

HTH
John
--
John Winters.  Wallingford, Oxon, England.

The Linux Emporium - the source for Linux CDs in the UK
See http://www.linuxemporium.co.uk/



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> When, and when not, should one cast a pointer?  For instance...  I have
> had someone tell me that casting a pointer from malloc() is of bad
> style.  Conversely, I have also had someone tell me that not casting a
> pointer from malloc() is bad style.  Without getting into reglious and
> preference issues, when and when should someone *not* cast a pointer?

> Sent via Deja.com http://www.deja.com/
> Before you buy.

C++ requires you to cast a void * to a pointer of another type, whilst C
doesn't. In C the code ptr = (char *) malloc(N); can hide a missing header,
whilst in C++ the header is required.

Bascially you need to cast the pointer if you want your code to compile under
C++. I'm doing this with my current project, for several reasons, but most
people don't think it is necessary to make most C code compile under C++, so
the consensus is don't cast void *s.

If cast from (say) int * to double * make sure you know what you are doing.
The cast tells the compiler to disable its normal error-checking.

Sent via Deja.com http://www.deja.com/
Before you buy.



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

>When, and when not, should one cast a pointer?

Don't cast pointers unless you can fully justify doing so. Pointer
casts are dangerous and if you find yourself using one then 9 times
out of 10 you are doing something wrong.

Quote:
> For instance...  I have
>had someone tell me that casting a pointer from malloc() is of bad
>style.

Correct.

Quote:
> Conversely, I have also had someone tell me that not casting a
>pointer from malloc() is bad style.

Casts tend to turn off compiler warnings. That;s unfortunate because
the compiler warnings for this sort of thing tend to tell you about
genuine errors in your code, like failing to include <stdlib.h> for
malloc().

Quote:
> Without getting into reglious and
>preference issues, when and when should someone *not* cast a pointer?

The general rule (for which there may be a few rare exception) is
don't cast pointers unless it is the only way to do something correctly.
Examples of that are ensuring that an argument in a variable argument
list has the correct type (notably casting NULL) and casting to
unsigned char * when you want to view an object as an array of bytes.

--
-----------------------------------------


-----------------------------------------



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:
>The cast tells the compiler to disable its normal error-checking.

Not always. Cast is necessary with variable arguments functions.

char x='A';
char y='B';

printf("%d %d\n,x,y);

will produce some funny jokes... (no complain from my ol'good BC 3.1)

printf("%d\n,(int)x,(int)y);

is the right way to do it.

For the records :

"%d" ([signed] int)
"%ld" ([signed] long [int])
"%u" (unsigned [int])
"%x" (unsigned [int])
"%X" (unsigned [int])
"%lx" (unsigned long [int])
"%lX" (unsigned long [int])
%s (char*) sign ?
%p (void*)
%i ?
...
complements welcome...

--
-hs-
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> char x='A';
> char y='B';

> printf("%d %d\n,x,y);

> will produce some funny jokes...

No, that is correct code.  `char' is promoted to `int' as part of
the default argument promotions.

Quote:
> (no complain from my ol'good BC 3.1)

Rightly so.

Quote:
> printf("%d\n,(int)x,(int)y);

> is the right way to do it.

It'll work (given the missing "), but it's overly complex.

--
"Under no circumstances, succumb to demands to write a glossary with
 the special purpose project vocabulary unambiguously defined.  Doing so
 would be unprofessional breach of the structured design principle of
 ``information hiding.''" --"How to Write Unmaintainable Code"



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?
I don't think so! Casts of this kind should be implicitly performed by
the compiler and you should NOT cast them in case you later on
redefine your variables and hide an error. As for your example:

On VC++ 5.0 in C mode:

#include <stdio.h>
int main()
{
        char a='a', b='b';
        printf("%d %d\n", a,b);
        return 0;

Quote:
}

Compiling...
clc_test.c

clc_test.obj - 0 error(s), 0 warning(s)



Quote:

>>The cast tells the compiler to disable its normal error-checking.

>Not always. Cast is necessary with variable arguments functions.

>char x='A';
>char y='B';

>printf("%d %d\n,x,y);

>will produce some funny jokes... (no complain from my ol'good BC 3.1)

>printf("%d\n,(int)x,(int)y);

>is the right way to do it.

>For the records :

>"%d" ([signed] int)
>"%ld" ([signed] long [int])
>"%u" (unsigned [int])
>"%x" (unsigned [int])
>"%X" (unsigned [int])
>"%lx" (unsigned long [int])
>"%lX" (unsigned long [int])
>%s (char*) sign ?
>%p (void*)
>%i ?
>...
>complements welcome...

Mark McIntyre

C- FAQ: http://www.eskimo.com/~scs/C-faq/top.html



Fri, 12 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> When, and when not, should one cast a pointer?  For instance...  I have
> had someone tell me that casting a pointer from malloc() is of bad
> style.  Conversely, I have also had someone tell me that not casting a
> pointer from malloc() is bad style.  Without getting into reglious and
> preference issues, when and when should someone *not* cast a pointer?

> Sent via Deja.com http://www.deja.com/
> Before you buy.

Casting the return pointer from malloc() is unnecessary, as malloc()
returns a generic void pointer. The "cast" is automagically made upon
assignment, and the pointer variable references the allocated memory
with its own scalar value.

char *ptr = (char *)malloc(50);
-------------^^^^^^
|
casts void pointer to a char pointer here (UNNECESSARY)

char *ptr = malloc(50);
^^^^^^^^^
|
char pointer conversion here

Omitting the cast has a further advantage of causing a good compiler to
issue error messages when stdlib.h is not included in the program. It is
cleaner, more helpful in debugging, and shows that you know what you're
doing.



Sat, 13 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

>Cast is necessary with variable arguments functions.

>char x='A';
>char y='B';

>printf("%d %d\n,x,y);

>will produce some funny jokes... (no complain from my ol'good BC 3.1)

No it won't. The integral promotions are applied to both arguments, so x and y
are passed as ints. gcc -Wformat won't complain either.

Quote:
>printf("%d\n,(int)x,(int)y);

>is the right way to do it.

The casts are unnecessary.

The example you may be thinking of is when you need to pass a pointer (usually a
null pointer) of a particular type to a variable argument function.

  void func(int value, ...);
  ...
    func(value, NULL);

is unsafe if func expects a char * as its second parameter. You need to use a
cast to ensure that the pointer passed is of the correct type.

    func(value, (char *)NULL);

Quote:
>For the records :

>"%d" ([signed] int)
>"%ld" ([signed] long [int])
>"%u" (unsigned [int])
>"%x" (unsigned [int])
>"%X" (unsigned [int])
>"%lx" (unsigned long [int])
>"%lX" (unsigned long [int])
>%s (char*) sign ?
>%p (void*)
>%i ?
>...
>complements welcome...

See

  http://www.dinkumware.com/htm_cl/lib_prin.html

for the full list.

-- Mat.



Sat, 13 Jul 2002 03:00:00 GMT  
 to cast or not to cast?


Quote:

> >The cast tells the compiler to disable its normal error-checking.

> Not always. Cast is necessary with variable arguments functions.

> char x='A';
> char y='B';

> printf("%d %d\n,x,y);

> will produce some funny jokes... (no complain from my ol'good BC 3.1)

> printf("%d\n,(int)x,(int)y);

> is the right way to do it.

Am I the only one for whom neither of these printfs will compile? Everyone
else seems to think they're both fine but, as far as I can see, they're
both a " short of a string literal...


Sat, 13 Jul 2002 03:00:00 GMT  
 to cast or not to cast?

Quote:

> Not always. Cast is necessary with variable arguments functions.

> char x='A';
> char y='B';

> printf("%d %d\n,x,y);

Unfortunately you've picked an example where it does work because of the
integral promotions.  However, there are plenty of cases where it really
would go wrong, e.g. if you were passing an 'int' but the function expected
a 'long'.  It is easy to overlook these because with prototyped functions
the compiler would do the necessary conversion for you.

Personally, I do tend to cast parameters to variadic functions whenever they
don't match the expected type.  Similarly I usually put casts in mixed-type
expressions like

  result = my_unsigned_long * (unsigned long int)my_signed_long;

even when they would produce the same result without.

This is for the ignoble reason that promotions and conversions are complex,
and I don't want to have to bother thinking about them.  There's also the
marginally-more-noble rationale that, while I may understand the rules for
this kind of stuff, the people who later maintain the code possibly won't.

Of course we are drifting somewhat from the original question, which was
about casting pointers.  I agree with other posters, that overuse of pointer
casts is a symptom to be viewed with some concern.

Cheers
Richard
--
The FAQ is at http://www.eskimo.com/~scs/C-faq/top.html
New users try http://www.sin.khk.be/~emulov/c.l.c/welcome_to_clc.htm



Sat, 13 Jul 2002 03:00:00 GMT  
 
 [ 13 post ] 

 Relevant Pages 

1. malloc: to cast or not to cast

2. Discarded Function Values (To Cast or Not to Cast)

3. When is a cast not a cast?

4. old style casts vs new style casts

5. casting of struct element void pointer casting

6. Cast...always cast...

7. Need help with reinterpret_cast, a C-style cast or function-style cast

8. old style casts vs new style casts

9. Need help with reinterpret_cast, a C-style cast or function-style cast

10. CString cast to LPCTSTR cast error

11. Need help with reinterpret_cast, a C-style cast or function-style cast

12. CString cast to LPCTSTR cast error

 

 
Powered by phpBB® Forum Software