Mail Archives: djgpp/2000/02/19/23:57:37
On 19 Feb 2000 13:44:37 GMT, "doug" <deleveld AT dds DOT nl> wrote:
> > In a nutshell: if you write C++, use new. If you write C, use
> > malloc(), and *don't* cast the return value, as it will actually hide
> > potential problems, instead of fixing any.
>
> Can you give me an example. I like my C programs to compile
> with as few warnings as possible, even if they are compiled as C++
Sorry. If you compile a program "as C++" it is a C++ program and not a
C program.
And there is no point compiling a valid C program "as C++" although
since Charles Petzold (in his excellent book "Programming windows")
recommended compiling C programs "as C++" people ruminate that this is
GOOD...
Imho the only profit you gain is that you have to do the malloc-cast
which is only a syntactical "ceremony" without any practical
usefulness.
But if you prefer C++ then stick to C++ by all means - but don't call
your programs C programs ;-) C and C++ are distinct languages with a
lot of similarities. And this "lot" is the dangerous part because it
makes you forget that there _are_ differences.
> and I cast the returned value from malloc to achieve this. Can you
> give me an example of where this casting may cause problems in
> a C program?
int main()
{
char* p = malloc(50);
}
Now you will get a diagnostic from a C compiler. As there is no
declaration for malloc in scope (because you forgot to #include
stdlib.h) the compiler will assume that malloc returns an int and
there is no implicit conversion from int to char*.
If you cast
char* p = (char*)malloc(50);
there is no diagnostic. The compiler still assumes that malloc returns
an int and assumes that the value returned by malloc is an int to be
casted to a char*. This is desastrous if int and char* have different
sizes and/or representations.
In C++ you have no option because you always have to cast explicitly.
The stdlib problem doesn't exist in C++ because in C++ it is an error
to call malloc without #including stdlib, while it is permitted in C.
Regards
Horst
- Raw text -