Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Casting the return value of malloc() ?

12 views
Skip to first unread message

Tinkertim

unread,
Oct 2, 2008, 5:22:04 AM10/2/08
to
Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.

For instance :

char *tmp = NULL;

tmp = (char *) malloc(1024);

Is there any pointing in casting the return value of malloc? I see
many people do that, but not test the result such as :

if (tmp == (char *) NULL)
.. some code about malloc() failing ...

Is there any point in casting it?

Cheers,
--Tim

Ian Collins

unread,
Oct 2, 2008, 5:44:19 AM10/2/08
to
Tinkertim wrote:
> Hi,
>
> I have often wondered if casting the return value of malloc() (or
> friends) actually helps anything, recent threads here suggest that it
> does not .. so I hope to find out.
>
> For instance :
>
> char *tmp = NULL;
>
> tmp = (char *) malloc(1024);
>
> Is there any pointing in casting the return value of malloc?

None what so ever.

--
Ian Collins.

Kenny McCormack

unread,
Oct 2, 2008, 5:44:38 AM10/2/08
to
In article <7ce1a426-30ed-47ee...@p49g2000hsd.googlegroups.com>,

Tinkertim <tink...@gmail.com> wrote:
>Hi,
>
>I have often wondered if casting the return value of malloc() (or
>friends) actually helps anything, recent threads here suggest that it
>does not .. so I hope to find out.

Good to see we're back on familiar ground.

Richard Heathfield

unread,
Oct 2, 2008, 5:51:11 AM10/2/08
to
Tinkertim said:

> Hi,
>
> I have often wondered if casting the return value of malloc() (or
> friends) actually helps anything,

What help do you think it offers? I can't think of any.

> recent threads here suggest that it
> does not .. so I hope to find out.
>
> For instance :
>
> char *tmp = NULL;
>
> tmp = (char *) malloc(1024);
>
> Is there any pointing in casting the return value of malloc?

It seems completely pointless to me. Do you have any reason for doing it?

> I see
> many people do that, but not test the result such as :
>
> if (tmp == (char *) NULL)
> .. some code about malloc() failing ...
>
> Is there any point in casting it?

Not that I can think of. Testing the return value, on the other hand, is
crucial.

I suggest you find someone who advocates the cast, and ask them why. Most
likely, they won't know. In the event that you find someone who does know
why they're casting, why not present this group with the reason he or she
gives you, and ask us what we think of it?

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999

Nick Keighley

unread,
Oct 2, 2008, 5:59:33 AM10/2/08
to

This is a FAQ
FAQ 7.7b "What's wrong with casting malloc's return value?"

the FAQ lives at http://c-faq.com

C++ requires a cast on the return of malloc(). But malloc()
is unusual in C++ code (an implementation of C++ might need it).
Some people write code that is required to compile under both C and
C++ (eg. library writers). They also might want to cast the return
value of malloc().


--
Nick Keighley

"Those are my principles. If you don't like them, I have others."
- Groucho Marx

polas

unread,
Oct 2, 2008, 7:42:26 AM10/2/08
to
On 2 Oct, 10:59, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:

> On 2 Oct, 10:22, Tinkertim <tinker...@gmail.com> wrote:
>
>
>
> > Hi,
>
> > I have often wondered if casting the return value of malloc() (or
> > friends) actually helps anything, recent threads here suggest that it
> > does not .. so I hope to find out.
>
> > For instance :
>
> > char *tmp = NULL;
>
> > tmp = (char *) malloc(1024);
>
> > Is there any pointing in casting the return value of malloc? I see
> > many people do that, but not test the result such as :
>
> > if (tmp == (char *) NULL)
> > .. some code about malloc() failing ...
>
> > Is there any point in casting it?
>
> This is a FAQ
> FAQ 7.7b "What's wrong with casting malloc's return value?"
>
> the FAQ lives athttp://c-faq.com

>
> C++ requires a cast on the return of malloc(). But malloc()
> is unusual in C++ code (an implementation of C++ might need it).
> Some people write code that is required to compile under both C and
> C++ (eg. library writers). They also might want to cast the return
> value of malloc().
>

As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted. Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly) from malloc and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour

Nick

--------
Mesham Parallel Programming Language
www.mesham.net

Richard Heathfield

unread,
Oct 2, 2008, 8:12:01 AM10/2/08
to
polas said:

<snip>



> As far as I understood it (which might be somewhat wrong) actually
> casting the return value is unwanted.

If you mean "unnecessary", you're right.

> Am I wrong that without
> including stdlib.h the return value is int (or int * cant remember
> which exactly) from malloc

In C90, whenever the compiler encounters any call to any function for which
it has not yet seen a declaration, it is required to assume that the
function returns int, even if We Know Different. (And indeed even if the
compiler knows different, which it is allowed to but not required to.)

Since you're assigning the value returned by malloc to a pointer object,
omitting the header therefore gives a type mismatch between int and
pointer, which the compiler is obliged to diagnose - UNLESS you foolishly
cast the diagnosis away.

If pointers are returned in a different way to ints, or if pointers are
longer than ints, or have completely different representations, this can
cause a very real problem.

> and so not casting the return value will
> provide a warning/error during compilation if you have missed this
> header? Whereas casting the value will hide this problem and result in
> strange behaviour

Yes, that's almost right - casting the value will hide the problem and
*may* result in strange behaviour. Or it may not. Until your boss is
watching...

polas

unread,
Oct 2, 2008, 8:13:33 AM10/2/08
to

Right, thanks for the help clearing that one up for me :)

Nick

Nick Keighley

unread,
Oct 2, 2008, 9:16:40 AM10/2/08
to
On 2 Oct, 12:42, polas <n...@helpforce.com> wrote:
> On 2 Oct, 10:59, Nick Keighley <nick_keighley_nos...@hotmail.com>
> wrote:
> > On 2 Oct, 10:22, Tinkertim <tinker...@gmail.com> wrote:

> > > I have often wondered if casting the return value of malloc() (or
> > > friends) actually helps anything, recent threads here suggest that it
> > > does not .. so I hope to find out.
>
> > > For instance :
>
> > > char *tmp = NULL;
>
> > > tmp = (char *) malloc(1024);
>
> > > Is there any pointing in casting the return value of malloc? I see
> > > many people do that, but not test the result such as :
>
> > > if (tmp == (char *) NULL)
> > > .. some code about malloc() failing ...
>
> > > Is there any point in casting it?
>
> > This is a FAQ
> > FAQ 7.7b "What's wrong with casting malloc's return value?"
>
> > the FAQ lives athttp://c-faq.com
>
> > C++ requires a cast on the return of malloc(). But malloc()
> > is unusual in C++ code (an implementation of C++ might need it).
> > Some people write code that is required to compile under both C and
> > C++ (eg. library writers). They also might want to cast the return
> > value of malloc().

and note the "C++" in my answer. C and C++ are different langauges
and the rules are slightly different. The C++ rules may in some
slightly obscure cases lead to C being written to C++ rules.

> As far as I understood it (which might be somewhat wrong) actually
> casting the return value is unwanted. Am I wrong that without
> including stdlib.h the return value is int (or int * cant remember
> which exactly)

int

> from malloc and so not casting the return value will
> provide a warning/error during compilation if you have missed this
> header? Whereas casting the value will hide this problem and result in
> strange behaviour

yes

--
Nick Keighley

CBFalconer

unread,
Oct 2, 2008, 7:19:13 PM10/2/08
to
Nick Keighley wrote:
>
... snip ...

>
> C++ requires a cast on the return of malloc(). But malloc() is
> unusual in C++ code (an implementation of C++ might need it).
> Some people write code that is required to compile under both C
> and C++ (eg. library writers). They also might want to cast the
> return value of malloc().

Not library writers. That would be an excellent way of installing
library bugs. However some people want to sell their software,
written in C source, to imbeciles who will simply compile it and
then use it. They want this to work even though the idiots are
using a C++ compiler. After all, why have a support call? Without
it the dumbos are happy, and the selling firm makes more money.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

Peter Nilsson

unread,
Oct 2, 2008, 7:54:13 PM10/2/08
to
Tinkertim <tinker...@gmail.com> wrote:
> I have often wondered if casting the return value
> of malloc() (or friends) actually helps anything,
> ...

You should first define what you mean by 'help', then
ask the more basic question of whether casts help
anything period.

--
Peter

Nick Keighley

unread,
Oct 3, 2008, 4:27:48 AM10/3/08
to
On 3 Oct, 00:19, CBFalconer <cbfalco...@yahoo.com> wrote:
> Nick Keighley wrote:

> > C++ requires a cast on the return of malloc(). But malloc() is
> > unusual in C++ code (an implementation of C++ might need it).
> > Some people write code that is required to compile under both C
> > and C++ (eg. library writers). They also might want to cast the
> > return value of malloc().
>
> Not library writers. That would be an excellent way of installing
> library bugs.

complete bollocks

> However some people want to sell their software,
> written in C source, to imbeciles who will simply compile it and
> then use it.

wow. imagine that people actually want to compile the source library
they bought/down loaded. And then they want to use it! I'd always
thought people bought source code so they could recycle it as
toilet paper.

Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.

> They want this to work even though the idiots are
> using a C++ compiler.

do you normally refer to customers as idiots?
I assume you are a hobbyist programmer that doesn't actually have
to deal with real-world customers and suppliers.

> After all, why have a support call? Without
> it the dumbos are happy, and the selling firm makes more money.

An example of someone who writes code that compiles with both
C and C++ is P.J.Plauger. Is he an imbecile or an idiot?

you are on the verge of a plonk


--
Nick Keighley

Kenny McCormack

unread,
Oct 3, 2008, 10:58:42 AM10/3/08
to
In article <8be39e8f-ccd3-4a22...@k30g2000hse.googlegroups.com>,
Nick Keighley <nick_keigh...@hotmail.com> wrote some good stuff,
leading up to:
...

>An example of someone who writes code that compiles with both
>C and C++ is P.J.Plauger. Is he an imbecile or an idiot?
>
>you are on the verge of a plonk

I'm not sure who is the better archetype of the senile old fool: CBF or
McBush.

Flash Gordon

unread,
Oct 3, 2008, 1:41:13 PM10/3/08
to
Nick Keighley wrote, On 03/10/08 09:27:

> On 3 Oct, 00:19, CBFalconer <cbfalco...@yahoo.com> wrote:
>> Nick Keighley wrote:
>
>>> C++ requires a cast on the return of malloc(). But malloc() is
>>> unusual in C++ code (an implementation of C++ might need it).
>>> Some people write code that is required to compile under both C
>>> and C++ (eg. library writers). They also might want to cast the
>>> return value of malloc().

In general library writers do not have to write code (apart from
possibly headers) so that it compiles as both C and C++ to make the
library available for use from both C and C++. Distribute build scripts
that will build it as C for most common implementations and, in general
(but not always) the problem is installed.

>> Not library writers. That would be an excellent way of installing
>> library bugs.
>
> complete bollocks

Well, it can lead to some bugs where the languages are subtly different.

>> However some people want to sell their software,
>> written in C source, to imbeciles who will simply compile it and
>> then use it.
>
> wow. imagine that people actually want to compile the source library
> they bought/down loaded. And then they want to use it! I'd always
> thought people bought source code so they could recycle it as
> toilet paper.

That does not require the code to be compilable in multiple languages.

> Yes C and C++ are different. But you can write a programs
> using a LARGE subset of C that will compile with C and C++.
> I know it is unfashionable to say this in clc.
> But it is none the less true.

Yes, it is true.

>> They want this to work even though the idiots are
>> using a C++ compiler.
>
> do you normally refer to customers as idiots?
> I assume you are a hobbyist programmer that doesn't actually have
> to deal with real-world customers and suppliers.

I've been known to call customers idiots because some are, I just don't
do it where the customers can here me!

>> After all, why have a support call? Without
>> it the dumbos are happy, and the selling firm makes more money.
>
> An example of someone who writes code that compiles with both
> C and C++ is P.J.Plauger. Is he an imbecile or an idiot?

I *think* he was calling the customers dumbos, not the authors of the
library.

I agree that there are sometimes good commercial reasons to produce code
that compilers as either language and works properly whichever language
is used. I just don't think it is really that common a requirement. I
think most people will be happy if a build script (makefile, batch file,
project file or whatever) is provided that build it appropriately and
header files that work and won't care what language it is compiled as.

> you are on the verge of a plonk
--

Flash Gordon
If spamming me sent it to sm...@spam.causeway.com
If emailing me use my reply-to address
See the comp.lang.c Wiki hosted by me at http://clc-wiki.net/

CBFalconer

unread,
Oct 3, 2008, 5:31:28 PM10/3/08
to
Flash Gordon wrote:
> Nick Keighley wrote:
>> CBFalconer <cbfalco...@yahoo.com> wrote:
>>
... snip ...

>>
>>> After all, why have a support call? Without it the dumbos are
>>> happy, and the selling firm makes more money.
>>
>> An example of someone who writes code that compiles with both
>> C and C++ is P.J.Plauger. Is he an imbecile or an idiot?
>
> I *think* he was calling the customers dumbos, not the authors of
> the library.

Exactly. And C library code is easily configured to be usable in
C++ systems, via the __cpluplus__ identifier. It still needs to be
compiled as C code, but can be linked into C++ systems. What more
do you really want?

Keith Thompson

unread,
Oct 3, 2008, 8:26:47 PM10/3/08
to
CBFalconer <cbfal...@yahoo.com> writes:
> Flash Gordon wrote:
>> Nick Keighley wrote:
>>> CBFalconer <cbfalco...@yahoo.com> wrote:
>>>
> ... snip ...
>>>
>>>> After all, why have a support call? Without it the dumbos are
>>>> happy, and the selling firm makes more money.
>>>
>>> An example of someone who writes code that compiles with both
>>> C and C++ is P.J.Plauger. Is he an imbecile or an idiot?
>>
>> I *think* he was calling the customers dumbos, not the authors of
>> the library.
>
> Exactly. And C library code is easily configured to be usable in
> C++ systems, via the __cpluplus__ identifier. It still needs to be
> compiled as C code, but can be linked into C++ systems. What more
> do you really want?

It's *also* possible to write code in the intersection of C and C++,
code that will behave correctly whether compiled with a C compiler or
with a C++ compiler. This can be useful if your customers doesn't
just need to call your code through the interfaces you've provided,
but to grab snippets to incorporate into their own C or C++ code
(assuming the license allows this).

Writing code that works properly both as C and as C++ requires some
care -- care that P.J. Plauger is eminently qualified to exercise.
But then, just writing code that works properly and portably in C
requires very nearly as much care.

The actual need to write code that's valid as both C and C++ is fairly
rare, but it's not nonexistent. If you want to disagree, that's fine
-- but you'll need better arguments than calling the customers
"dumbos".

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

Flash Gordon

unread,
Oct 4, 2008, 3:36:24 AM10/4/08
to
Keith Thompson wrote, On 04/10/08 01:26:

> CBFalconer <cbfal...@yahoo.com> writes:
>> Flash Gordon wrote:
>>> Nick Keighley wrote:
>>>> CBFalconer <cbfalco...@yahoo.com> wrote:
>>>>
>> ... snip ...
>>>>> After all, why have a support call? Without it the dumbos are
>>>>> happy, and the selling firm makes more money.
>>>> An example of someone who writes code that compiles with both
>>>> C and C++ is P.J.Plauger. Is he an imbecile or an idiot?
>>> I *think* he was calling the customers dumbos, not the authors of
>>> the library.
>> Exactly. And C library code is easily configured to be usable in
>> C++ systems, via the __cpluplus__ identifier. It still needs to be
>> compiled as C code, but can be linked into C++ systems. What more
>> do you really want?

I stated it was possible in the post you replied to, although I did not
specify the mechanism. I know the mechanism, it just was not relevant. I
said that the prefered way of distribution it as source would be to
include build scripts which invoke a compiler for the correct language
and that in my opinion this covers most requirements.

> It's *also* possible to write code in the intersection of C and C++,
> code that will behave correctly whether compiled with a C compiler or
> with a C++ compiler. This can be useful if your customers doesn't
> just need to call your code through the interfaces you've provided,
> but to grab snippets to incorporate into their own C or C++ code
> (assuming the license allows this).

It is also useful if customer A will pay you _small_fortune_ for the
code explicitly requiring that it be C++ code and customer B will pay
you _small_fortune_ for the code explicitly requiring that it is C code.
Remember that neither customer will care about the other customers
requirements. Remember also that a lot of people are writing code for
money, so if customers want to pay enough we will do things the hard
ways, especially if the alternative is greatly reduced profits.

> Writing code that works properly both as C and as C++ requires some
> care -- care that P.J. Plauger is eminently qualified to exercise.
> But then, just writing code that works properly and portably in C
> requires very nearly as much care.
>
> The actual need to write code that's valid as both C and C++ is fairly
> rare, but it's not nonexistent. If you want to disagree, that's fine
> -- but you'll need better arguments than calling the customers
> "dumbos".

In my opinion the commercial argument for writing code that is valid and
correct as both languages is valid even if the customers *are* "dumbos".

If what the customer wants is legal (in the sense of no laws being
broken), possible, something you don't have a moral objection to, and
something you can do profitably, then it can be the right thing to do
even if there are better technical solutions.

Old Wolf

unread,
Oct 4, 2008, 1:40:42 PM10/4/08
to
On Oct 3, 10:27 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:

> Yes C and C++ are different. But you can write a programs
> using a LARGE subset of C that will compile with C and C++.
> I know it is unfashionable to say this in clc.
> But it is none the less true.

The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran. But again, why would you?

Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot

What's your reason?

Malcolm McLean

unread,
Oct 4, 2008, 2:13:48 PM10/4/08
to

"Old Wolf" <old...@inspire.net.nz> wrote in message

Programs in the common subset of Fortran and C are fit only for the
international obfuscated C competition. Rules may even allow submission to
the Fortran equivalent at the same time.

Now one good question is why use C at all when C++ is a near as makes no
difference a superset of it? However let's say that we decide that we want
to discourage people from using object-orientation, because of certain
drawbacks we see in the methodogy. A politically effective way of doing this
is to ban C++.

OK, so here's a fragment of our C program

void encrypt(unsigned char *data, size_t len)
{
int i;

for(i=0;i<len;i++)
data ^= 0xCC;
}

A few weeks later, the terrible news come through. Our encryption has been
compromised. We need a beter method, and fast.

So we dust off our Sedgewick and realise that there is somethign called the
RSA cryptosystem. This is very much better, and it is not too difficult to
implment, as long as you have a huge integer library. Well we've got one,
but it's in C++.

No problem. Change the file extension to .cpp, and drop in

void encrypt(unsigned char *data, size_t len)
{
bignum prime1(13);
bignum prime2(17);
bignum unfactorisable = prime1 * prime2;

/* (etc) */
}

Now we're back in business. Nothing else needs to be changed. We've dropped
in an emergency C++ bignum library and the code is now C++ and won't compile
under C, but that is small price for turning out our improved encryption on
time.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Keith Thompson

unread,
Oct 4, 2008, 2:40:33 PM10/4/08
to

As we've mentioned several times in this thread, P.J. Plauger seems to
have sound business reasons for doing this. He's posted about it
here; Google it.

Ian Collins

unread,
Oct 4, 2008, 3:57:11 PM10/4/08
to
3) Testing/Simulation.

The first C code I ever built C as C++ as a device driver. In C,
hardware registers were typedefs to an integer type. In C++ the
register types were classes that simulated the hardware behaviour when
read a written. I still use this technique today for testing drivers.

We also compiled application code as C++ to get stricter type checking,
but C compilers and lint have improved considerably in this area.

--
Ian Collins.

Richard Bos

unread,
Oct 6, 2008, 3:42:39 AM10/6/08
to
Keith Thompson <ks...@mib.org> wrote:

> Old Wolf <old...@inspire.net.nz> writes:
> > On Oct 3, 10:27 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>

> >> Yes C and C++ are different. But you can write a programs
> >> using a LARGE subset of C that will compile with C and C++.

True, but in the general case they'll be both bad C and worse C++.
_Correct_, yes, but horrible style.

> > The question is, why would you want to do this?
> >
> > You can write programs that compile in both C
> > and Fortran. But again, why would you?
> >
> > Here's the reasons I can think of:
> > 1) For curiosity's sake
> > 2) You are an idiot
> >
> > What's your reason?
>
> As we've mentioned several times in this thread, P.J. Plauger seems to
> have sound business reasons for doing this.

He does, but so far, he's the only one who has managed to convince me
that _in his specific case_, the advantages outweigh the downsides. In
every other case I've seen, the claim that "but I might want to compile
my C code as C++" is very simply put aside with the argument that you
just should not do that, as there are mechanisms in C++ to make such
half-hearted practices superfluous.

Richard

Keith Thompson

unread,
Oct 6, 2008, 3:49:55 AM10/6/08
to
r...@hoekstra-uitgeverij.nl (Richard Bos) writes:
> Keith Thompson <ks...@mib.org> wrote:
>> Old Wolf <old...@inspire.net.nz> writes:
>> > On Oct 3, 10:27 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
>> >> Yes C and C++ are different. But you can write a programs
>> >> using a LARGE subset of C that will compile with C and C++.
>
> True, but in the general case they'll be both bad C and worse C++.
> _Correct_, yes, but horrible style.

As far as I know, the only thing you need to do that I'd consider poor
C style is casting the result of malloc -- and more generally, not
taking advantage of C's implicit conversions for void*.

I'm sure a lot of programmers trying to write code that's compatible
with both C and C++ will write stylistically bad code -- but then a
lot of programmers manage to do that trying to write plain C.

[...]

>> As we've mentioned several times in this thread, P.J. Plauger seems to
>> have sound business reasons for doing this.
>
> He does, but so far, he's the only one who has managed to convince me
> that _in his specific case_, the advantages outweigh the downsides. In
> every other case I've seen, the claim that "but I might want to compile
> my C code as C++" is very simply put aside with the argument that you
> just should not do that, as there are mechanisms in C++ to make such
> half-hearted practices superfluous.

Agreed. *Most* programmers don't need to write code that compiles as
both C and C++ (and far too many think they do). But to suggest that
*everyone* who does so is stupid, or has stupid customers, is absurd.

RocTheEngy

unread,
Oct 6, 2008, 5:29:06 PM10/6/08
to

> Not that I can think of. Testing the return value, on the other hand, is
> crucial.
>
> I suggest you find someone who advocates the cast, and ask them why. Most
> likely, they won't know. In the event that you find someone who does know
> why they're casting, why not present this group with the reason he or she
> gives you, and ask us what we think of it?
>
> --
> Richard Heathfield <http://www.cpax.org.uk>
> Email: -http://www. +rjh@
> Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
> "Usenet is a strange place" - dmr 29 July 1999


The professor at my college where I learned C (he was newly hired at
the time; almost 20 years ago) was the first person to teach C at
the university. Previous programming classes were purely pascal.

He was therefore, by defacto standard, the "guru" and not to be
questioned... (at least not by us undergrads).

He was _adamant_ that the malloc() family *required* casts. To this
day,
the only answer I recall him giving is "...to give the compiler a
warm,
fuzzy feeling". To inquire further left one with the feeling that
your next test grade may suffer if you pressed him. Looking back, I
suspect the intimidation was to avoid embarrasment.

The system, as best I recall, was some type of VAX. It ran a flavor
of Unix, and we compiled our code with "cc" (not gcc). I used that
programming convention for years on many platforms until I read the
CLC FAQ.

To this day, many of us would like to know WHY we were
required to cast for malloc's. I wish I could remember more details.
For all I now, he may have had a reason. Beats me.

Richard Heathfield

unread,
Oct 6, 2008, 5:35:19 PM10/6/08
to
RocTheEngy said:

>
>> Not that I can think of. Testing the return value, on the other hand, is
>> crucial.
>>
>> I suggest you find someone who advocates the cast, and ask them why.
>> Most likely, they won't know. In the event that you find someone who
>> does know why they're casting, why not present this group with the
>> reason he or she gives you, and ask us what we think of it?
>>

> The professor at my college where I learned C (he was newly hired at
> the time; almost 20 years ago) was the first person to teach C at
> the university. Previous programming classes were purely pascal.
>
> He was therefore, by defacto standard, the "guru" and not to be
> questioned... (at least not by us undergrads).
>
> He was _adamant_ that the malloc() family *required* casts.

20 years ago, he was *right*.

The language changed... 19 years ago.

RocTheEngy

unread,
Oct 6, 2008, 5:34:56 PM10/6/08
to
> "Usenet is a strange place" - dmr 29 July 1999- Hide quoted text -
>
> - Show quoted text -

I said _almost_ 20 years ago. :) It was 1991...

But to understand your statement; there was a time when this
convention was correct?
(i.e. required)

Ian Collins

unread,
Oct 6, 2008, 5:39:38 PM10/6/08
to
RocTheEngy wrote:
>
> I said _almost_ 20 years ago. :) It was 1991...
>
> But to understand your statement; there was a time when this
> convention was correct?
> (i.e. required)
>
Before C was standardised, void wasn't part of the language and malloc
returned char*

--
Ian Collins.

Peter Nilsson

unread,
Oct 6, 2008, 6:03:03 PM10/6/08
to
Flash Gordon <s...@spam.causeway.com> wrote:
> Nick Keighley wrote, On 03/10/08 09:27:
> > An example of someone who writes code that compiles
> > with both C and C++ is P.J.Plauger.

Let's not forget Ritchie and Kernighan.

> > Is he an imbecile or an idiot?
>
> I *think* he was calling the customers dumbos, not the
> authors of the library.

Plauger shares the view of his customers. So any criticism
of his customers must be applied to Plauger himself, if
consistency is to hold.

Here's what he had to say in 2004...

"What I find interesting about this debate is the two
positions being espoused:

1) Omitting casts on malloc calls is acceptable, but
not necessarily virtuous.

2) Putting casts on malloc calls is stupid.

Those of us in the first camp are going to keep using
casts, and we're going to keep respecting those who
don't. It would be nice if we were granted a bit of
respect in turn, but what the hell. A closed mind
avoids the risk of having to change."

--
Peter

Flash Gordon

unread,
Oct 7, 2008, 8:12:53 PM10/7/08
to
Peter Nilsson wrote, On 06/10/08 23:03:

> Flash Gordon <s...@spam.causeway.com> wrote:
>> Nick Keighley wrote, On 03/10/08 09:27:
>>> An example of someone who writes code that compiles
>>> with both C and C++ is P.J.Plauger.
>
> Let's not forget Ritchie and Kernighan.

That was because there were no compilers conforming to ANSI C at the
time so they had to use a C++ compiler to get access to certain features.

>>> Is he an imbecile or an idiot?
>> I *think* he was calling the customers dumbos, not the
>> authors of the library.
>
> Plauger shares the view of his customers. So any criticism
> of his customers must be applied to Plauger himself, if
> consistency is to hold.

I thought that his view was that it was the right thing for him to do it
because that was his customers' requirement.

> Here's what he had to say in 2004...
>
> "What I find interesting about this debate is the two
> positions being espoused:
>
> 1) Omitting casts on malloc calls is acceptable, but
> not necessarily virtuous.
>
> 2) Putting casts on malloc calls is stupid.

He missed a view some espouse...

3) Putting casts on malloc is virtuous

> Those of us in the first camp are going to keep using
> casts, and we're going to keep respecting those who
> don't. It would be nice if we were granted a bit of
> respect in turn, but what the hell. A closed mind
> avoids the risk of having to change."

Well, at least some of the people who in general strongly disagree with
putting the casts in have accepted that sometimes there is a good
reason. So not everyone who is against casting has a completely closed
mind :-)

Ian Collins

unread,
Oct 7, 2008, 9:14:48 PM10/7/08
to
Flash Gordon wrote:
> Peter Nilsson wrote, On 06/10/08 23:03:
>> Flash Gordon <s...@spam.causeway.com> wrote:
>>> Nick Keighley wrote, On 03/10/08 09:27:
>>>> An example of someone who writes code that compiles
>>>> with both C and C++ is P.J.Plauger.
>> Let's not forget Ritchie and Kernighan.
>
> That was because there were no compilers conforming to ANSI C at the
> time so they had to use a C++ compiler to get access to certain features.
>
Like void!

I don't think the original K&R even mentions malloc. They do briefly
describe calloc, which is shown as returning char* so a cast is required.

--
Ian Collins.

Peter Nilsson

unread,
Oct 8, 2008, 1:31:52 AM10/8/08
to
Flash Gordon <s...@spam.causeway.com> wrote:
> Peter Nilsson wrote, On 06/10/08 23:03:
> > Flash Gordon <s...@spam.causeway.com> wrote:
> >> Nick Keighley wrote, On 03/10/08 09:27:
> >>> An example of someone who writes code that compiles
> >>> with both C and C++ is P.J.Plauger.
> > Let's not forget Ritchie and Kernighan.
>
> That was because there were no compilers conforming to
> ANSI C at the time so they had to use a C++ compiler to
> get access to certain features.

<http://groups.google.com/group/comp.lang.c/msg/4a6ea4a63a610cac?
dmode=source>

> >>> Is he an imbecile or an idiot?
> >> I *think* he was calling the customers dumbos, not the
> >> authors of the library.
> >
> > Plauger shares the view of his customers. So any criticism
> > of his customers must be applied to Plauger himself, if
> > consistency is to hold.
>
> I thought that his view was that it was the right thing for
> him to do it because that was his customers' requirement.

<http://groups.google.com/group/comp.lang.c/msg/02411d85b17ce318?
dmode=source>

<snip>

--
Peter

Nick Keighley

unread,
Oct 8, 2008, 3:46:36 AM10/8/08
to
On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.com> wrote:

> I don't think the original K&R even mentions malloc.  

pp 143 and 167

--
Nick Keighley

Ian Collins

unread,
Oct 8, 2008, 4:09:38 AM10/8/08
to
Nick Keighley wrote:
> On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.com> wrote:
>
>> I don't think the original K&R even mentions malloc.
>
> pp 143 and 167
>
Not in my 1979 printing. You are thinking of K&R2.

--
Ian Collins.

Nick Keighley

unread,
Oct 8, 2008, 4:11:09 AM10/8/08
to
On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nz> wrote:
> On Oct 3, 10:27 pm,Nick Keighley<nick_keighley_nos...@hotmail.com>

> wrote:
>
> > Yes C and C++ are different. But you can write a programs
> > using a LARGE subset of C that will compile with C and C++.
> > I know it is unfashionable to say this in clc.
> > But it is none the less true.
>
> The question is, why would you want to do this?
>
> You can write programs that compile in both C
> and Fortran.

that's just dumb. Try thinking instead of just repeating dogma.
Fortran doesn't look anything like C. Well written C compiles
with C++. That is a fact.

> But again, why would you?
>
> Here's the reasons I can think of:
>   1) For curiosity's sake
>   2) You are an idiot

whatever.

--
Nick Keighley

Ian Collins

unread,
Oct 8, 2008, 4:14:00 AM10/8/08
to
Nick Keighley wrote:
> On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nz> wrote:
>> On Oct 3, 10:27 pm,Nick Keighley<nick_keighley_nos...@hotmail.com>
>> wrote:
>>
>>> Yes C and C++ are different. But you can write a programs
>>> using a LARGE subset of C that will compile with C and C++.
>>> I know it is unfashionable to say this in clc.
>>> But it is none the less true.
>> The question is, why would you want to do this?
>>
>> You can write programs that compile in both C
>> and Fortran.
>
> that's just dumb. Try thinking instead of just repeating dogma.
> Fortran doesn't look anything like C. Well written C compiles
> with C++. That is a fact.
>
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

--
Ian Collins.

Nick Keighley

unread,
Oct 8, 2008, 4:19:12 AM10/8/08
to

ah! missed the word "original"! And I don't have
K&R1 at my elbow

--
nick keighley

Ian Collins

unread,
Oct 8, 2008, 4:25:04 AM10/8/08
to
Nick Keighley wrote:
> On 8 Oct, 09:09, Ian Collins <ian-n...@hotmail.com> wrote:
>> Nick Keighley wrote:
>>> On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.com> wrote:
>>>> I don't think the original K&R even mentions malloc.
>>> pp 143 and 167
>> Not in my 1979 printing. You are thinking of K&R2.
>
> ah! missed the word "original"! And I don't have
> K&R1 at my elbow
>
Nor did I until I read your post!

--
Ian Collins.

Richard Heathfield

unread,
Oct 8, 2008, 4:38:21 AM10/8/08
to
Ian Collins said:

> Nick Keighley wrote:

<snip>

>> Well written C compiles with C++. That is a fact.
>>
> No it is not. The common subset of C and C++ compiles as C and C++.
> There are a number of C constructs that are not valid C++.

And they are "well-written" constructs, too.

Nick, are you really saying that adding a cast to a call to a function
returning void * is either badly-written C or legal C++?

James Kuyper

unread,
Oct 8, 2008, 7:02:36 AM10/8/08
to
Nick Keighley wrote:
> On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nz> wrote:
>> On Oct 3, 10:27 pm,Nick Keighley<nick_keighley_nos...@hotmail.com>
>> wrote:
>>
>>> Yes C and C++ are different. But you can write a programs
>>> using a LARGE subset of C that will compile with C and C++.
>>> I know it is unfashionable to say this in clc.
>>> But it is none the less true.
>> The question is, why would you want to do this?
>>
>> You can write programs that compile in both C
>> and Fortran.
>
> that's just dumb. Try thinking instead of just repeating dogma.
> Fortran doesn't look anything like C. ...

Fortran code can also BE C code - with care, it can even behave in
equivalent ways when compiled with both types of compilers. Of course,
this relies upon complicated tricks that depend upon the different ways
in which the two languages handle comments. No one would recommend doing
so, which I believe was his whole point: it's possible, but why do it?

That approach wouldn't work with C and C++; they're too similar - with
the release of C99 they now have identical syntax for comments. However,
they are also sufficiently similar that you don't need to use that
approach, so the reference to Fortran was a bad argument.

> ... Well written C compiles


> with C++. That is a fact.

It is a falsehood that bears a resemblance to the truth. C can be
written to compile with C++, and most of the restrictions needed to make
it compile with C++ are things that make the C code better (such as
mandatory use of prototypes). C code that compiles under C++ will
usually (but not always) behave the same way as when compiled under C.
With a little bit of additional care, it is possible to modify almost
any strictly conforming C90 program (and most C programs that don't
strictly conform to C90) so that it will compile with the same behavior
under either C or C++. An obvious exception is programs which are
designed to detect which language they were compiled with.

However, well written C code does NOT cast the value returned by
malloc(); and such code is a constraint violation for C++, unless the
destination is also a void*. Well written C code can and sometimes does
make use of identifiers that are reserved in C++. Also, well written C99
code can make use of constructs that are not supported by C++. Many C99
features will be supported in future versions of C++, but that hasn't
happened yet, and many features will never be supported.

Richard Tobin

unread,
Oct 8, 2008, 7:45:01 AM10/8/08
to
In article <0dabe2de-7b59-4ea0...@s20g2000prd.googlegroups.com>,
Nick Keighley <nick_keigh...@hotmail.com> wrote:

>Well written C compiles with C++. That is a fact.

In that case, to write C well you have to refer to a C++ reference,
because C++ reserves identifiers that a C programmer would otherwise
have no reason to avoid.

-- Richard
--
Please remember to mention me / in tapes you leave behind.

Nick Keighley

unread,
Oct 8, 2008, 10:49:59 AM10/8/08
to
On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
> Ian Collins said:
> > Nick Keighley wrote:

> >> Well written C compiles with C++. That is a fact.
>
> > No it is not.  The common subset of C and C++ compiles as C and C++.
> > There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?
I'm aware that a fair amount of C99 stuff is unlikely
to make it into C++ (eg. complex numbers).


> And they are "well-written" constructs, too.
>
> Nick, are you really saying that adding a cast to a call to a function
> returning void * is either badly-written C or legal C++?

er, no.

char *fred = (char*)malloc(42);

is not particularly good C but it will compile with C++.

--
Nick Keighley


James Kuyper

unread,
Oct 8, 2008, 11:17:15 AM10/8/08
to
Nick Keighley wrote:
> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
>> Ian Collins said:
>>> Nick Keighley wrote:
>
>>>> Well written C compiles with C++. That is a fact.
>>> No it is not. The common subset of C and C++ compiles as C and C++.
>>> There are a number of C constructs that are not valid C++.
>
> a couple of people have said this. Are they C89 constructs?

Yes, many of them are. See appendix C of the C++ standard. It's 15 pages
long. Many of the constructs are very uncommon, many of them will never
appear in well-written C code. But some of them do occur with moderate
frequency even in well-written C code.


Richard Heathfield

unread,
Oct 8, 2008, 11:59:26 AM10/8/08
to
Nick Keighley said:

> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
>> Ian Collins said:
>> > Nick Keighley wrote:
>
>> >> Well written C compiles with C++. That is a fact.
>>
>> > No it is not. The common subset of C and C++ compiles as C and C++.
>> > There are a number of C constructs that are not valid C++.
>
> a couple of people have said this. Are they C89 constructs?

Sure. Several keywords, for a start, and automatic void * conversion.

<snip>

>> Nick, are you really saying that adding a cast to a call to a function
>> returning void * is either badly-written C or legal C++?
>
> er, no.

Of course I got that the wrong way round (sigh). I meant to ask whether you
really thought *not* adding a cast is either badly-written C or legal C++.

> char *fred = (char*)malloc(42);
>
> is not particularly good C but it will compile with C++.

We were discussing well-written C, were we not? The well-written equivalent
of the above:

char *buf = malloc(n);

is *not* legal C++.

Keith Thompson

unread,
Oct 8, 2008, 11:57:34 AM10/8/08
to
Peter Nilsson <ai...@acay.com.au> writes:
> Flash Gordon <s...@spam.causeway.com> wrote:
>> Peter Nilsson wrote, On 06/10/08 23:03:
>> > Flash Gordon <s...@spam.causeway.com> wrote:
>> >> Nick Keighley wrote, On 03/10/08 09:27:
>> >>> An example of someone who writes code that compiles
>> >>> with both C and C++ is P.J.Plauger.
>> > Let's not forget Ritchie and Kernighan.
>>
>> That was because there were no compilers conforming to
>> ANSI C at the time so they had to use a C++ compiler to
>> get access to certain features.
>
> <http://groups.google.com/group/comp.lang.c/msg/4a6ea4a63a610cac?
> dmode=source>

In which Bjarne Stroustrup writes:
| Dennis Ritchie and Brian Kernighan are among the most thoughtful of
| people. They did have a choice at the time. If they had thought it
| important/best to leave malloc calls uncast they could have (1) used
| the ANSI C compiler or (2) edited the casts out in the final draft
| (after the final check with the ANSI C compiler) or (3) politely asked
| me for a compatibility feature in Cfront (we talked almost every day).
|
| I think it is safest to assume that when Dennis Ritchie and Brian
| Kernighan did something, it was because they wanted to do that and not
| the opposite.

But the errata list for K&R2 acknowledges that casting the result of
malloc isn't such a good idea after all.
<http://netlib.bell-labs.com/cm/cs/cbook/2ediffs.html>:

142 (section 6.5, toward the end): The remark about casting the
return value of malloc ("the proper method is to declare ... then
explicitly coerce") needs to be rewritten. The example is correct
and works, but the advice is debatable in the context of the
1988-1989 ANSI/ISO standards. It's not necessary (given that
coercion of void * to ALMOSTANYTYPE * is automatic), and possibly
harmful if malloc, or a proxy for it, fails to be declared as
returning void *. The explicit cast can cover up an unintended
error. On the other hand, pre-ANSI, the cast was necessary, and it
is in C++ also.

>> >>> Is he an imbecile or an idiot?
>> >> I *think* he was calling the customers dumbos, not the
>> >> authors of the library.
>> >
>> > Plauger shares the view of his customers. So any criticism
>> > of his customers must be applied to Plauger himself, if
>> > consistency is to hold.
>>
>> I thought that his view was that it was the right thing for
>> him to do it because that was his customers' requirement.
>
> <http://groups.google.com/group/comp.lang.c/msg/02411d85b17ce318?
> dmode=source>

In which P.J. Plauger, replying to Richard Heathfield, writes:
| I thought I had given more than one reason, en passant, but here's a
| quick review. Indeed the first motivation we had for adding casts to
| malloc calls was to satisfy a market need to have all our Standard C
| library compile either as C or C++. The C++ Standard (thanks to me)
| deliberately permits the C library to have either extern "C" or
| extern "C++" linkage -- and we have serious customers for both
| flavors. Having done so, we then found reasons to make *all* of our
| C source code compilable as C++.
|
| Generally I avoid casts for the reason so often given -- they're so
| strong that they often hide problems. We add them where required for
| correctness, for portability, for C++ compatibility, and to quiet
| silly warnings. Our experience over the years is that the last
| category of casts do indeed raise the cost of maintenance -- we fix
| something here and the forgotten consequences there are masked by
| the cast, until we discover the bug by a painful runtime trace.
|
| But allocator casts often *help* us find bugs that arise during
| maintenance. The classic pattern is a structure declared here,
| containing a pointer to another structure declared somewhere else,
| for which storage is allocated there, and freed some other
| there. That's why we allocate N times the size of the thing we
| really want, cast the resultant pointer to a pointer to that type,
| and store it in what should be a compatible type of pointer. We've
| had the compiler inform us of bugs in both size and pointer types as
| the code changes under maintenance and enhancement.
|
| In our environment, bugs like failing to include stdlib.h get found
| and fixed in the first pass or two of code writing. We generally
| perform *many* passes over our code during development, and develop
| a companion set of tests. So the kind of bugs masked by casts on
| malloc are cheap to fix, while the kind exposed by such casts are
| much more expensive.

But I believe the bugs exposed by casting the result of malloc can be
avoided by using the clc-recommended idiom:

ptr = malloc(COUNT * sizeof *ptr);

even if "ptr" is some more complex expression.

Keith Thompson

unread,
Oct 8, 2008, 12:56:42 PM10/8/08
to
Richard Heathfield <r...@see.sig.invalid> writes:
> Nick Keighley said:
>
>> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
>>> Ian Collins said:
>>> > Nick Keighley wrote:
>>
>>> >> Well written C compiles with C++. That is a fact.
>>>
>>> > No it is not. The common subset of C and C++ compiles as C and C++.
>>> > There are a number of C constructs that are not valid C++.
>>
>> a couple of people have said this. Are they C89 constructs?
>
> Sure. Several keywords, for a start, and automatic void * conversion.

You mean C++ keywords that are valid C89 identifiers, right? On first
reading, I thought you were talking about C keywords.

[...]

vipp...@gmail.com

unread,
Oct 8, 2008, 1:08:03 PM10/8/08
to
> Nick Keighley <nick_keighley_nos...@hotmail.com> wrote:
> Well written C compiles with C++. That is a fact.

It may be the case that it's correct C but not correct C++, and vice
versa.
Here's one of the best pages I've found on the net about C/C++
differences:
<http://david.tribble.com/text/cdiffs.htm>

Here's some code that doesn't work in C++, but does work in C,

#include <limits.h>

int main(void) {
char m[sizeof 'A'];
return m[CHAR_BIT == 8] = 0;
}

This takes advantage of the following difference, that 'A' in C has
type int, but in C++ has type char.
In C this code always works; in C++ it never works.

Keith Thompson

unread,
Oct 8, 2008, 1:59:58 PM10/8/08
to

Incorrect. If sizeof(int)==1 (which implies CHAR_BIT>=16), then it
can work in both C and C++.

Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;
}

Such examples are irrelevant to Nick's claim that "Well written C
compiles with C++.", unless you want to claim that either of the above
examples is well written.

Nick's claim is incorrect because well written C does not cast the
result of malloc (and calloc, and realloc). Avoiding that issue
requires writing code that's less than ideal in C for the sake of C++
compatibility. (Avoiding C++ keywords is less of an issue, since well
written C code doesn't *need* to use them as identifiers.)

vipp...@gmail.com

unread,
Oct 8, 2008, 2:15:47 PM10/8/08
to
On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.org> wrote:

> vipps...@gmail.com writes:
> >> Nick Keighley <nick_keighley_nos...@hotmail.com> wrote:
> >> Well written C compiles with C++. That is a fact.
>
> > It may be the case that it's correct C but not correct C++, and vice
> > versa.
> > Here's one of the best pages I've found on the net about C/C++
> > differences:
> > <http://david.tribble.com/text/cdiffs.htm>
>
> > Here's some code that doesn't work in C++, but does work in C,
>
> > #include <limits.h>
>
> > int main(void) {
> > char m[sizeof 'A'];
> > return m[CHAR_BIT == 8] = 0;
> > }
>
> > This takes advantage of the following difference, that 'A' in C has
> > type int, but in C++ has type char.
> > In C this code always works; in C++ it never works.
>
> Incorrect. If sizeof(int)==1 (which implies CHAR_BIT>=16), then it
> can work in both C and C++.

Ah yes, correctly noted.

> Sure, there are plenty of contrived examples of code that works in C
> but not in C++. Here's another one:
>
> int main(void)
> {
> #ifdef __cplusplus
> #error
> #endif
> return 0;
>
> }

Unless the implementation defines __cplusplus ;-)

> Such examples are irrelevant to Nick's claim that "Well written C
> compiles with C++.", unless you want to claim that either of the above
> examples is well written.

Depends on what Nick means with well written, but let's not stretch
it, I agree.

> Nick's claim is incorrect because well written C does not cast the
> result of malloc (and calloc, and realloc). Avoiding that issue
> requires writing code that's less than ideal in C for the sake of C++
> compatibility. (Avoiding C++ keywords is less of an issue, since well
> written C code doesn't *need* to use them as identifiers.)

I also agree.

james...@verizon.net

unread,
Oct 8, 2008, 2:51:33 PM10/8/08
to
vipps...@gmail.com wrote:
> On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.org> wrote:
...

> > Sure, there are plenty of contrived examples of code that works in C
> > but not in C++. Here's another one:
> >
> > int main(void)
> > {
> > #ifdef __cplusplus
> > #error
> > #endif
> > return 0;
> >
> > }
>
> Unless the implementation defines __cplusplus ;-)

That's not permitted for a conforming implementation ot C99
(6.10.8p5). I think that was permitted in C90, but I'm not sure. It
was never good QoI, at least not at any time since the birth of C++.

Keith Thompson

unread,
Oct 8, 2008, 2:51:50 PM10/8/08
to
vipp...@gmail.com writes:
> On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.org> wrote:
[...]

>> Sure, there are plenty of contrived examples of code that works in C
>> but not in C++. Here's another one:
>>
>> int main(void)
>> {
>> #ifdef __cplusplus
>> #error
>> #endif
>> return 0;
>>
>> }
>
> Unless the implementation defines __cplusplus ;-)
[...]

A conforming C99 implementation is not allowed to do so. (C90 doesn't
have this rule.)

Ian Collins

unread,
Oct 8, 2008, 4:01:32 PM10/8/08
to
Nick Keighley wrote:
> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
>> Ian Collins said:
>>> Nick Keighley wrote:
>
>>>> Well written C compiles with C++. That is a fact.
>>> No it is not. The common subset of C and C++ compiles as C and C++.
>>> There are a number of C constructs that are not valid C++.
>
> a couple of people have said this. Are they C89 constructs?

Yes, the stricter C++ rules for enums are an obvious example.

--
Ian Collins.

Richard Heathfield

unread,
Oct 8, 2008, 10:37:10 PM10/8/08
to
Keith Thompson said:

> Richard Heathfield <r...@see.sig.invalid> writes:
>> Nick Keighley said:
>>
>>> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
>>>> Ian Collins said:
>>>> > Nick Keighley wrote:
>>>
>>>> >> Well written C compiles with C++. That is a fact.
>>>>
>>>> > No it is not. The common subset of C and C++ compiles as C and C++.
>>>> > There are a number of C constructs that are not valid C++.
>>>
>>> a couple of people have said this. Are they C89 constructs?
>>
>> Sure. Several keywords, for a start, and automatic void * conversion.
>
> You mean C++ keywords that are valid C89 identifiers, right?

Yes.

> On first reading, I thought you were talking about C keywords.

Lazy phrasing on my part. Sorry.

Richard Heathfield

unread,
Oct 8, 2008, 10:42:59 PM10/8/08
to
james...@verizon.net said:

> vipps...@gmail.com wrote:
>> On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.org> wrote:
> ...
>> > Sure, there are plenty of contrived examples of code that works in C
>> > but not in C++. Here's another one:
>> >
>> > int main(void)
>> > {
>> > #ifdef __cplusplus
>> > #error
>> > #endif
>> > return 0;
>> >
>> > }
>>
>> Unless the implementation defines __cplusplus ;-)
>
> That's not permitted for a conforming implementation ot C99
> (6.10.8p5).

True, but of little relevance for the time being.

> I think that was permitted in C90, but I'm not sure.

It was.

> It
> was never good QoI, at least not at any time since the birth of C++.

Why is it not good QoI? It is not the job of any programming language to
avoid treading on the toes of another language. Would we criticise an
implementation's QoI for using the identifier ENVIRONMENT (which is
reserved, like __cplusplus) just because it clashes with COBOL?

Ian Collins

unread,
Oct 8, 2008, 11:08:12 PM10/8/08
to
Richard Heathfield wrote:
> james...@verizon.net said:
>> vipps...@gmail.com wrote:

>>> Unless the implementation defines __cplusplus ;-)
>> That's not permitted for a conforming implementation ot C99
>> (6.10.8p5).
>
> True, but of little relevance for the time being.
>

Now now Richard, some of us do use platforms where the native compiler
is C99.

>> It
>> was never good QoI, at least not at any time since the birth of C++.
>
> Why is it not good QoI? It is not the job of any programming language to
> avoid treading on the toes of another language. Would we criticise an
> implementation's QoI for using the identifier ENVIRONMENT (which is
> reserved, like __cplusplus) just because it clashes with COBOL?
>

How often does C share system or standard library headers with COBOL?
Try putting #define __cplusplus before #include <stdio.h> and see how
far your compiler gets.

--
Ian Collins.

Richard Heathfield

unread,
Oct 9, 2008, 12:03:54 AM10/9/08
to
Ian Collins said:

> Richard Heathfield wrote:
>> james...@verizon.net said:
>>> vipps...@gmail.com wrote:
>
>>>> Unless the implementation defines __cplusplus ;-)
>>> That's not permitted for a conforming implementation ot C99
>>> (6.10.8p5).
>>
>> True, but of little relevance for the time being.
>>
> Now now Richard, some of us do use platforms where the native compiler
> is C99.

Sure - and there are some people who do fly on the Space Shuttle. Tips on
drinking whisky in a zero-g environment will be very useful to *them*, no
doubt, but they are still of little relevance in general terms. When we
have a few million people up in orbit, the relevance of such tips will
increase. And, perhaps a little while after that, C99 might even start
catching on among implementors.

>>> It
>>> was never good QoI, at least not at any time since the birth of C++.
>>
>> Why is it not good QoI? It is not the job of any programming language to
>> avoid treading on the toes of another language. Would we criticise an
>> implementation's QoI for using the identifier ENVIRONMENT (which is
>> reserved, like __cplusplus) just because it clashes with COBOL?
>>
> How often does C share system or standard library headers with COBOL?

Been there, done that, not funny. Also beside the point.

> Try putting #define __cplusplus before #include <stdio.h> and see how
> far your compiler gets.

No, I can't do that, because __cplusplus starts with two consecutive
underscores, which means it's reserved for the implementation. I'm tempted
to add "duh!", but I'll try to refrain.

Ian Collins

unread,
Oct 9, 2008, 12:41:23 AM10/9/08
to
Richard Heathfield wrote:
> Ian Collins said:
>
>> Richard Heathfield wrote:
>>> james...@verizon.net said:
>>>> vipps...@gmail.com wrote:
>>>>> Unless the implementation defines __cplusplus ;-)
>>>> That's not permitted for a conforming implementation ot C99
>>>> (6.10.8p5).
>>> True, but of little relevance for the time being.
>>>
>> Now now Richard, some of us do use platforms where the native compiler
>> is C99.
>
> Sure - and there are some people who do fly on the Space Shuttle.

There's rather a lot more Solaris and AIX developers than space shuttle
passengers.

>> Try putting #define __cplusplus before #include <stdio.h> and see how
>> far your compiler gets.
>
> No, I can't do that, because __cplusplus starts with two consecutive
> underscores, which means it's reserved for the implementation.

You can't, but you might be a compiler implementer who's tempted to add
the define to one of your implementation's headers. Doing so would be a
great way to limit sales.

--
Ian Collins.

Richard Heathfield

unread,
Oct 9, 2008, 12:53:35 AM10/9/08
to
Ian Collins said:

> Richard Heathfield wrote:
>> Ian Collins said:
>>
>>> Richard Heathfield wrote:
>>>> james...@verizon.net said:
>>>>> vipps...@gmail.com wrote:
>>>>>> Unless the implementation defines __cplusplus ;-)
>>>>> That's not permitted for a conforming implementation ot C99
>>>>> (6.10.8p5).
>>>> True, but of little relevance for the time being.
>>>>
>>> Now now Richard, some of us do use platforms where the native compiler
>>> is C99.
>>
>> Sure - and there are some people who do fly on the Space Shuttle.
>
> There's rather a lot more Solaris and AIX developers than space shuttle
> passengers.

Nevertheless, C99 users are a vanishingly small percentage of the C
programming population. The analogy is, I think, a reasonable one.

>
>>> Try putting #define __cplusplus before #include <stdio.h> and see how
>>> far your compiler gets.
>>
>> No, I can't do that, because __cplusplus starts with two consecutive
>> underscores, which means it's reserved for the implementation.
>
> You can't, but you might be a compiler implementer who's tempted to add
> the define to one of your implementation's headers. Doing so would be a
> great way to limit sales.

Well, I'm not - and in any case, because C99 forbids __cplusplus and
because I program in the common subset of C89 and C99, I couldn't define
__cplusplus even if I were an implementor.

CBFalconer

unread,
Oct 9, 2008, 12:55:12 AM10/9/08
to
Ian Collins wrote:
>
... snip ...

>
> How often does C share system or standard library headers with
> COBOL? Try putting #define __cplusplus before #include <stdio.h>
> and see how far your compiler gets.

That identifier is reserved for the implementation.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

Ian Collins

unread,
Oct 9, 2008, 1:02:28 AM10/9/08
to
Richard Heathfield wrote:
> Ian Collins said:
>
>> Richard Heathfield wrote:
>>> Ian Collins said:
>>>
>>>> Richard Heathfield wrote:
>>>>> james...@verizon.net said:
>>>>>> vipps...@gmail.com wrote:
>>>>>>> Unless the implementation defines __cplusplus ;-)
>>>>>> That's not permitted for a conforming implementation ot C99
>>>>>> (6.10.8p5).
>>>>> True, but of little relevance for the time being.
>>>>>
>>>> Now now Richard, some of us do use platforms where the native compiler
>>>> is C99.
>>> Sure - and there are some people who do fly on the Space Shuttle.
>> There's rather a lot more Solaris and AIX developers than space shuttle
>> passengers.
>
> Nevertheless, C99 users are a vanishingly small percentage of the C
> programming population. The analogy is, I think, a reasonable one.
>
I think the ratio is somewhat less than 100000000:1, which is about
right for shuttle passengers in the global population.

--
Ian Collins.

Ian Collins

unread,
Oct 9, 2008, 1:04:31 AM10/9/08
to
CBFalconer wrote:
> Ian Collins wrote:
> .... snip ...

>> How often does C share system or standard library headers with
>> COBOL? Try putting #define __cplusplus before #include <stdio.h>
>> and see how far your compiler gets.
>
> That identifier is reserved for the implementation.
>
The lost quote from James was "I think that was permitted in C90, but
I'm not sure. It was never good QoI, at least not at any time since the
birth of C++."

QoI applies to the implementation.

--
Ian Collins.

Richard Heathfield

unread,
Oct 9, 2008, 1:14:55 AM10/9/08
to
Ian Collins said:

However much you try to avoid the issue, there aren't very many people
using C99 implementations.

Richard Bos

unread,
Oct 9, 2008, 2:48:36 AM10/9/08
to
Nick Keighley <nick_keigh...@hotmail.com> wrote:

> On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalid> wrote:
> > Ian Collins said:
> > > Nick Keighley wrote:
>
> > >> Well written C compiles with C++. That is a fact.

^^^^^^^^^^^^
Ahem.

> > And they are "well-written" constructs, too.
> >
> > Nick, are you really saying that adding a cast to a call to a function
> > returning void * is either badly-written C or legal C++?
>
> er, no.
>
> char *fred = (char*)malloc(42);
>
> is not particularly good C but it will compile with C++.

^^^^^^^^^^^^^^^^^^^^^
Ahem.

Contradiction?

Richard

James Kuyper

unread,
Oct 9, 2008, 7:39:50 AM10/9/08
to
Richard Heathfield wrote:
> james...@verizon.net said:
>
>> vipps...@gmail.com wrote:
...

>>> Unless the implementation defines __cplusplus ;-)
...

>> It
>> was never good QoI, at least not at any time since the birth of C++.
>
> Why is it not good QoI? It is not the job of any programming language to
> avoid treading on the toes of another language.

QoI means doing more than the minimum requirement; it means actually
being useful to the user. Code which is written to compile under either
C or C++, achieving that portability with the help of checks for
__cplusplus, is a reality, however much you personally may disapprove of
it. A C90 compiler that predefines __cplusplus is going to cause
problems for such code, and the fact that it was legal for the
implementation to do so won't make it's justifiably angry customers any
happier about that fact.


> ... Would we criticise an

> implementation's QoI for using the identifier ENVIRONMENT (which is
> reserved, like __cplusplus) just because it clashes with COBOL?

COBOL is not sufficiently similar to C to encourage the writing of code
that is meaningfully compilable in both languages. I don't remember
enough about COBOL to be sure whether it's possible to use the same kind
of commenting tricks that allow you to write a Fortran program that also
compiles as a C program - but in any event that's not what I'm talking
about.

For C and C++, it's possible to write a program where code which is not
inside a comment, in either language, and which survives conditional
compilation in both languages, constitutes the majority of a significant
program, and gets compiled with essentially the same interpretation in
both languages. That's not possible for C and COBOL.

The ENVIRONMENT keyword was not defined by COBOL for the specific
purpose of allowing a program compilable by both languages to determine
which language it was being compiled for. Also, it is far more plausible
that a C implementation would have a legitimate non-malicious reason to
use ENVIRONMENT, than it is for __cplusplus.

For all these reasons, I wouldn't dream of criticizing a C
implementation that made use of an ENVIRONMENT identifier; I would
criticize any C90 compiler that used a legal loophole to justify
predefining a __cplusplus macro.

Richard Heathfield

unread,
Oct 9, 2008, 8:04:03 AM10/9/08
to
James Kuyper said:

<snip>



> QoI means doing more than the minimum requirement; it means actually
> being useful to the user.

The most useful thing a C compiler could do on encountering __cplusplus
would be to #error That's C++. This is a C compiler. Duh.

> Code which is written to compile under either
> C or C++, achieving that portability with the help of checks for
> __cplusplus, is a reality, however much you personally may disapprove of
> it.

If the code is legal C and legal C++, it will either be bad C, bad C++, or
both. Daft idea. Silly to pander to daft ideas. Harumph, etc.

Jean-Marc Bourguet

unread,
Oct 9, 2008, 8:39:32 AM10/9/08
to
Richard Heathfield <r...@see.sig.invalid> writes:

> The most useful thing a C compiler could do on encountering __cplusplus
> would be to #error That's C++. This is a C compiler. Duh.

That's the most stupidiest thing a C compiler could do.

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

is something which is very sensible to put on headers designed to be used
in C (while providing the implementation of the functions there declared)
as well as in C++ (which use that code).

While the interest of compiling function definition in C as well as in C++
is debatable -- I think it is sometimes usefull and my estimation of the
number of cases where it is seems to be somewhere between your estimation
and James' -- having common headers for both languages is usefull.

Yours,

--
Jean-Marc

Richard Tobin

unread,
Oct 9, 2008, 8:56:34 AM10/9/08
to
In article <JNOdnezU1LyPb3DV...@bt.com>,
Richard Heathfield <r...@see.sig.invalid> wrote:

>> QoI means doing more than the minimum requirement; it means actually
>> being useful to the user.

>The most useful thing a C compiler could do on encountering __cplusplus
>would be to #error That's C++. This is a C compiler. Duh.

Surely the point of __cplusplus is to allow code to be conditionalised
for the two languages.

>If the code is legal C and legal C++, it will either be bad C, bad C++, or
>both. Daft idea. Silly to pander to daft ideas. Harumph, etc.

A header file conditionalised for inclusion in both C and C++ is
certainly ugly, but I don't think it's necessarily a daft idea to
write such header files. It seems like a design flaw that C++
routinely requires such conditionalisation though.

-- Richard
--
Please remember to mention me / in tapes you leave behind.

James Kuyper

unread,
Oct 9, 2008, 10:09:53 AM10/9/08
to
Richard Heathfield wrote:
> James Kuyper said:
>
> <snip>
>
>> QoI means doing more than the minimum requirement; it means actually
>> being useful to the user.
>
> The most useful thing a C compiler could do on encountering __cplusplus
> would be to #error That's C++. This is a C compiler. Duh.

Not if it's being used to determine whether to conditionally include C
code or C++ code, by someone who wants the compiler to compile it as C
code. The only "useful" thing about treating it as a #error is that it
informs the user that he's selected the wrong C compiler for this purpose.

>> Code which is written to compile under either
>> C or C++, achieving that portability with the help of checks for
>> __cplusplus, is a reality, however much you personally may disapprove of
>> it.
>
> If the code is legal C and legal C++, it will either be bad C, bad C++, or
> both. Daft idea. Silly to pander to daft ideas. Harumph, etc.

I disagree that it's daft. Whether or not it's daft, it's moderately
popular. Even if it were daft, the simple fact that it is also popular
is sufficient to make predefinition of __cplusplus bad QoI.

Richard Heathfield

unread,
Oct 9, 2008, 10:45:25 AM10/9/08
to
Jean-Marc Bourguet said:

> Richard Heathfield <r...@see.sig.invalid> writes:
>
>> The most useful thing a C compiler could do on encountering __cplusplus
>> would be to #error That's C++. This is a C compiler. Duh.
>
> That's the most stupidiest thing a C compiler could do.

Clearly, opinions differ.

>
> #ifdef __cplusplus
> extern "C" {
> #endif
>
> ...
>
> #ifdef __cplusplus
> }
> #endif
>
> is something which is very sensible to put on headers designed to be used
> in C (while providing the implementation of the functions there declared)
> as well as in C++ (which use that code).

In C89, it can result in a diagnostic message and the failure of the
translation. And opening oneself up to that problem is pretty stupid too.

If you want to use a header in C and yet have access to that header in C++,
it's trivial to do without breaking either language's rules:

/* C header - cheader.h */

#ifndef H_CHEADER
#define H_CHEADER 1
int foo(void); /* or whatever */
#endif

/* C++ header - cppheader.h */
#ifndef H_CPPHEADER
#define H_CPPHEADER 1
extern "C"
{
#include "cheader.h"
}
#endif

<snip>

Richard Tobin

unread,
Oct 9, 2008, 11:07:00 AM10/9/08
to
In article <9MqdnUHodrR5inPV...@bt.com>,
Richard Heathfield <r...@see.sig.invalid> wrote:

>In C89, it can result in a diagnostic message and the failure of the
>translation. And opening oneself up to that problem is pretty stupid too.

Do you know of any real implementations where this is true? So much
widely-used software uses #ifdef __cplusplus that I would have thought
that rejecting it would be a serious barrier to sales.

CBFalconer

unread,
Oct 9, 2008, 11:04:23 AM10/9/08
to
Richard Heathfield wrote:
> James Kuyper said:
>
> <snip>
>
>> QoI means doing more than the minimum requirement; it means
>> actually being useful to the user.
>
> The most useful thing a C compiler could do on encountering
> __cplusplus would be to #error That's C++. This is a C compiler.

Not so. We want the universal use in the header file. I.e:

#ifdef __cplusplus
extern "C"
{
#endif

... normal header file ...
#ifdef __cplusplus
}
#endif

and now the module is callable from C and C++.

Richard Heathfield

unread,
Oct 9, 2008, 11:40:44 AM10/9/08
to
CBFalconer said:

> Richard Heathfield wrote:
>> James Kuyper said:
>>
>> <snip>
>>
>>> QoI means doing more than the minimum requirement; it means
>>> actually being useful to the user.
>>
>> The most useful thing a C compiler could do on encountering
>> __cplusplus would be to #error That's C++. This is a C compiler.
>
> Not so. We want the universal use in the header file.

No, we don't. We want a clear delineation between the two languages.

> I.e:
>
> #ifdef __cplusplus
> extern "C"
> {
> #endif
> ... normal header file ...
> #ifdef __cplusplus
> }
> #endif
>
> and now the module is callable from C and C++.

At the cost of introducing a syntax error into the C code, protected by the
flimsiest of defences.

Richard Heathfield

unread,
Oct 9, 2008, 11:41:57 AM10/9/08
to
Richard Tobin said:

> In article <9MqdnUHodrR5inPV...@bt.com>,
> Richard Heathfield <r...@see.sig.invalid> wrote:
>
>>In C89, it can result in a diagnostic message and the failure of the
>>translation. And opening oneself up to that problem is pretty stupid too.
>
> Do you know of any real implementations where this is true?

Do you know that one won't be released tomorrow, with such fantastic
compensating advantages that everyone flocks to it despite its strident
approach to __cplusplus?

Richard Tobin

unread,
Oct 9, 2008, 12:05:53 PM10/9/08
to
In article <w6idnewXqcq5uHPV...@bt.com>,
Richard Heathfield <r...@see.sig.invalid> wrote:

>>>In C89, it can result in a diagnostic message and the failure of the
>>>translation. And opening oneself up to that problem is pretty stupid too.

>> Do you know of any real implementations where this is true?

>Do you know that one won't be released tomorrow, with such fantastic
>compensating advantages that everyone flocks to it despite its strident
>approach to __cplusplus?

I'm pretty sure of that, yes. Certainly sure enough not to worry
about using __cplusplus.

james...@verizon.net

unread,
Oct 9, 2008, 12:21:08 PM10/9/08
to
Richard Heathfield wrote:
> CBFalconer said:
>
> > Richard Heathfield wrote:
> >> James Kuyper said:
> >>
> >> <snip>
> >>
> >>> QoI means doing more than the minimum requirement; it means
> >>> actually being useful to the user.
> >>
> >> The most useful thing a C compiler could do on encountering
> >> __cplusplus would be to #error That's C++. This is a C compiler.
> >
> > Not so. We want the universal use in the header file.
>
> No, we don't. We want a clear delineation between the two languages.

Both of you are use "we"; I'm not sure who "we" is in each case, but
it's clear that the two of you are using the terms to describe non-
overlapping sets of people. Why don't the two of you both go back to
"I", unless you are willing to define who "we" are, with sufficiently
precision to clearly exclude the other person?

I have no objection to a "clear delineation between the two
languages", but for me a "clear delineation" means that it's easy for
code which has been written to compile using either language to
determine which language it is being compiled for, which is obviously
incompatible with the meaning that you attach to that phrase.

Richard Heathfield

unread,
Oct 9, 2008, 3:01:07 PM10/9/08
to
james...@verizon.net said:

> Richard Heathfield wrote:
>> CBFalconer said:
>>

<snip>


>> > Not so. We want the universal use in the header file.
>>
>> No, we don't. We want a clear delineation between the two languages.
>
> Both of you are use "we"; I'm not sure who "we" is in each case,

Clearly it's intended to mean "all the bright people". How accurately it is
being used is another matter. :-)

> I have no objection to a "clear delineation between the two
> languages", but for me a "clear delineation" means that it's easy for
> code which has been written to compile using either language to
> determine which language it is being compiled for, which is obviously
> incompatible with the meaning that you attach to that phrase.

For me, it means use a C++ compiler to compile C++ code, and use a C
compiler to compile C code.

Keith Thompson

unread,
Oct 9, 2008, 3:35:19 PM10/9/08
to
Richard Heathfield <r...@see.sig.invalid> writes:
> james...@verizon.net said:
[...]

>> I have no objection to a "clear delineation between the two
>> languages", but for me a "clear delineation" means that it's easy for
>> code which has been written to compile using either language to
>> determine which language it is being compiled for, which is obviously
>> incompatible with the meaning that you attach to that phrase.
>
> For me, it means use a C++ compiler to compile C++ code, and use a C
> compiler to compile C code.

For you, and for most *but not all* C and/or C++ programmers who know
what they're doing.

But, for example, the C++ standard requires support for the C standard
headers; "#include <stdlib.h>" is valid C++ ( "#include <cstdlib>" is
usually preferred, but both are valid). In a typical implementation,
it makes sense to have a single "/usr/include/stdlib.h" file that's
usable by either C or C++ code, using the __cplusplus symbol to
differentiate. Yes, you could do it with two separate files, but then
you'd have to have either a different naming scheme or a different
header search path for the C and C++ compilers. Why add that
complication when it's not necessary? And why not allow authors of C
libraries to make their headers usable for C++ programmers as well?

Sure, the C90 standard doesn't forbid a C implementation to predefine
__cplusplus -- but a compiler that did so would be exhibiting a DS9K
level of perversity (or a serious configuration error in a combined C
and C++ implementation that had better be fixed before the product
sees the light of day). Henry Spencer's warning goes both ways: if
the compiler lies to me, I will get my revenge. It would take a
deliberate blindness to anything outside ISO/IEC 9899:1990 to pretend
that a C compiler that predefines __cplusplus isn't lying.

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

Ian Collins

unread,
Oct 9, 2008, 4:04:47 PM10/9/08
to
Richard Heathfield wrote:
> CBFalconer said:
>
>> Richard Heathfield wrote:
>>> James Kuyper said:
>>>
>>> <snip>
>>>
>>>> QoI means doing more than the minimum requirement; it means
>>>> actually being useful to the user.
>>> The most useful thing a C compiler could do on encountering
>>> __cplusplus would be to #error That's C++. This is a C compiler.
>> Not so. We want the universal use in the header file.
>
> No, we don't. We want a clear delineation between the two languages.
>
>> I.e:
>>
>> #ifdef __cplusplus
>> extern "C"
>> {
>> #endif
>> ... normal header file ...
>> #ifdef __cplusplus
>> }
>> #endif
>>
>> and now the module is callable from C and C++.
>
> At the cost of introducing a syntax error into the C code, protected by the
> flimsiest of defences.
>
Tell that to just about every platform's standard library writers and
give then a good laugh.

--
Ian Collins.

Ian Collins

unread,
Oct 9, 2008, 4:06:23 PM10/9/08
to
Richard Heathfield wrote:
>
> If the code is legal C and legal C++, it will either be bad C, bad C++, or
> both. Daft idea. Silly to pander to daft ideas. Harumph, etc.
>
This is your blinkered view, not fact. Some of us have good technical
reasons to compile some of our C with a C++ compiler.

--
Ian Collins.

Malcolm McLean

unread,
Oct 9, 2008, 4:37:09 PM10/9/08
to

"Keith Thompson" <ks...@mib.org> wrote in message
>In a typical implementation,
> it makes sense to have a single "/usr/include/stdlib.h" file that's
> usable by either C or C++ code, using the __cplusplus symbol to
> differentiate. Yes, you could do it with two separate files, but then
> you'd have to have either a different naming scheme or a different
> header search path for the C and C++ compilers.
>
But why should the C be uglified with a C++ construct?

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Ian Collins

unread,
Oct 9, 2008, 4:45:24 PM10/9/08
to
Malcolm McLean wrote:
>
> "Keith Thompson" <ks...@mib.org> wrote in message
>> In a typical implementation,
>> it makes sense to have a single "/usr/include/stdlib.h" file that's
>> usable by either C or C++ code, using the __cplusplus symbol to
>> differentiate. Yes, you could do it with two separate files, but then
>> you'd have to have either a different naming scheme or a different
>> header search path for the C and C++ compilers.

> But why should the C be uglified with a C++ construct?

Because library writers want their headers to be useful?

How often do you read system headers?

--
Ian Collins.

Keith Thompson

unread,
Oct 9, 2008, 5:18:13 PM10/9/08
to
"Malcolm McLean" <regn...@btinternet.com> writes:
> "Keith Thompson" <ks...@mib.org> wrote in message
>>In a typical implementation,
>> it makes sense to have a single "/usr/include/stdlib.h" file that's
>> usable by either C or C++ code, using the __cplusplus symbol to
>> differentiate. Yes, you could do it with two separate files, but then
>> you'd have to have either a different naming scheme or a different
>> header search path for the C and C++ compilers.
>>
> But why should the C be uglified with a C++ construct?

For the reasons I stated above.

Implementations of the standard C headers are already quite ugly on
most systems.

CBFalconer

unread,
Oct 9, 2008, 7:57:50 PM10/9/08
to
Richard Heathfield wrote:
> CBFalconer said:
>> Richard Heathfield wrote:
>>> James Kuyper said:
>>>
>>> <snip>
>>>
>>>> QoI means doing more than the minimum requirement; it means
>>>> actually being useful to the user.
>>>
>>> The most useful thing a C compiler could do on encountering
>>> __cplusplus would be to #error That's C++. This is a C compiler.
>>
>> Not so. We want the universal use in the header file.
>
> No, we don't. We want a clear delineation between the two languages.
>
>> I.e:
>> #ifdef __cplusplus
>> extern "C"
>> {
>> #endif
>> ... normal header file ...
>> #ifdef __cplusplus
>> }
>> #endif
>>
>> and now the module is callable from C and C++.
>
> At the cost of introducing a syntax error into the C code,
> protected by the flimsiest of defences.

No. Protected by the fact that the C standard (the present one,
for C99) specifies that the implementation must not define
__cplusplus. I believe that that name was picked only after
considering as many C compilers as possible, and it was determined
that the requirement would not conflict in any known extant C90
compilers.

CBFalconer

unread,
Oct 9, 2008, 8:03:00 PM10/9/08
to
Keith Thompson wrote:
> "Malcolm McLean" <regn...@btinternet.com> writes:
>> "Keith Thompson" <ks...@mib.org> wrote:
>>
>>> In a typical implementation, it makes sense to have a single
>>> "/usr/include/stdlib.h" file that's usable by either C or C++
>>> code, using the __cplusplus symbol to differentiate. Yes, you
>>> could do it with two separate files, but then you'd have to
>>> have either a different naming scheme or a different header
>>> search path for the C and C++ compilers.
>>
>> But why should the C be uglified with a C++ construct?
>
> For the reasons I stated above.
>
> Implementations of the standard C headers are already quite ugly
> on most systems.

I see no C++ construct in:

#ifdef __cplusplus
/* something */
#endif

CBFalconer

unread,
Oct 9, 2008, 8:05:45 PM10/9/08
to

Why? A C compiler is smaller, and more accurate for compiling C
code. No C++ compiler is needed.

Ian Collins

unread,
Oct 9, 2008, 8:55:41 PM10/9/08
to
CBFalconer wrote:
> Ian Collins wrote:
>> Richard Heathfield wrote:
>>
>>> If the code is legal C and legal C++, it will either be bad C,
>>> bad C++, or both. Daft idea. Silly to pander to daft ideas.
>>> Harumph, etc.
>> This is your blinkered view, not fact. Some of us have good
>> technical reasons to compile some of our C with a C++ compiler.
>
> Why? A C compiler is smaller, and more accurate for compiling C
> code. No C++ compiler is needed.
>
As I've posted before; I use C++ simulations of hardware to test driver
code. I use typedefs to integer types for registers when compiling in C
for target hardware and C++ classes when compiling as C++ on my
development host. The C++ classes are used to simulate the hardware
behaviour and interface with the test harness when the registers are
read from or written to.

If there was a way to do this in C, I would use C, but there isn't. The
utility of the technique more than justifies the compromises in the C code.

--
Ian Collins

James Kuyper

unread,
Oct 9, 2008, 9:19:08 PM10/9/08
to
Richard Heathfield wrote:
...

> Do you know that one won't be released tomorrow, with such fantastic
> compensating advantages that everyone flocks to it despite its strident
> approach to __cplusplus?

I'd expect such a "strident approach" to be anti-correlated with the
attitudes needed to produce a compiler with "fantastic compensating
advantages".

Richard Heathfield

unread,
Oct 10, 2008, 3:22:59 AM10/10/08
to
CBFalconer said:

> Richard Heathfield wrote:
>> CBFalconer said:

<snip>


>>>
>>> and now the module is callable from C and C++.
>>
>> At the cost of introducing a syntax error into the C code,
>> protected by the flimsiest of defences.
>
> No. Protected by the fact that the C standard (the present one,
> for C99)

Chortle chortle chortle, chuckle chuckle, etc etc. Ha and, in fact, ha.
Etc, etc. </smile>

Furrfu, Chuck!

Nick Keighley

unread,
Oct 10, 2008, 3:39:27 AM10/10/08
to

hallelujah!
Richard is inhabiting a bizzare parallel universe on this one

--
Nick Keighley

Richard Heathfield

unread,
Oct 10, 2008, 4:35:43 AM10/10/08
to
Ian Collins said:

> Richard Heathfield wrote:
>>
>> If the code is legal C and legal C++, it will either be bad C, bad C++,
>> or both. Daft idea. Silly to pander to daft ideas. Harumph, etc.
>>
> This is your blinkered view, not fact.

NO, sir! It's my blinkered view, AND fact! :-)

> Some of us have good technical
> reasons to compile some of our C with a C++ compiler.

I've never heard a convincing reason for doing this - including P J
Plauger's reason. But of course I respect your choice. And so, it appears,
do implementers!

Ian Collins

unread,
Oct 10, 2008, 5:37:19 AM10/10/08
to
Richard Heathfield wrote:
> Ian Collins said:
>
>> Richard Heathfield wrote:
>>> If the code is legal C and legal C++, it will either be bad C, bad C++,
>>> or both. Daft idea. Silly to pander to daft ideas. Harumph, etc.
>>>
>> This is your blinkered view, not fact.
>
> NO, sir! It's my blinkered view, AND fact! :-)
>
>> Some of us have good technical
>> reasons to compile some of our C with a C++ compiler.
>
> I've never heard a convincing reason for doing this - including P J
> Plauger's reason. But of course I respect your choice. And so, it appears,
> do implementers!
>
What isn't convincing about my main reason?

--
Ian Collins

Richard Heathfield

unread,
Oct 10, 2008, 7:17:58 AM10/10/08
to
James Kuyper said:

Just you wait, James - you'll eat your words when I finally release my
amazing super-duper C compiler... any century now.

Richard Heathfield

unread,
Oct 10, 2008, 7:23:17 AM10/10/08
to
Nick Keighley said:

It's much sunnier over here. JOIN US!

Richard Heathfield

unread,
Oct 10, 2008, 7:29:50 AM10/10/08
to
Ian Collins said:

Well, I certainly wouldn't do it that way. If I have understood you
correctly, you're using one set of code for development, and a very
different set of code (and indeed a different language!) for testing.
Okay, I'm not going to say it was a bad decision, but it does go against
what I would consider to be good test design principles.

Ian Collins

unread,
Oct 10, 2008, 4:21:25 PM10/10/08
to
Richard Heathfield wrote:
> Ian Collins said:
>
>> Richard Heathfield wrote:
>>> Ian Collins said:
>>>
>>>> Richard Heathfield wrote:
>>>>> If the code is legal C and legal C++, it will either be bad C, bad
>>>>> C++, or both. Daft idea. Silly to pander to daft ideas. Harumph, etc.
>>>>>
>>>> This is your blinkered view, not fact.
>>> NO, sir! It's my blinkered view, AND fact! :-)
>>>
>>>> Some of us have good technical
>>>> reasons to compile some of our C with a C++ compiler.
>>> I've never heard a convincing reason for doing this - including P J
>>> Plauger's reason. But of course I respect your choice. And so, it
>>> appears, do implementers!
>>>
>> What isn't convincing about my main reason?
>
> Well, I certainly wouldn't do it that way. If I have understood you
> correctly, you're using one set of code for development, and a very
> different set of code (and indeed a different language!) for testing.

Not different code, same code, different types for some bits of hardware
along the lines of:

#if defined __cplusplus

struct StatusRegister
{
/* Handle writes
*/
StatusRegister& operator=( uint8_t );

/* Handle reads
*/
operator uint8_t() const;
};

#else

typedef uint8_t StatusRegister;

#endif

Although in practice I'd split the header into C and C++ versions.

All the rest of the code is unchanged. I adopted this technique to
avoid having code littered with ugly #ifded TEST block I've seen
elsewhere. I believe the code under test should be the code used in
production and that the code should be as free of conditional compiles
as possible. I hate conditional compile blocks, they destroy the flow
when reeding code.

> Okay, I'm not going to say it was a bad decision, but it does go against
> what I would consider to be good test design principles.
>

There's more than one level of testing. My unit tests don't use C++ for
the target code. Hardware registers are just a block of memory shared
by the target code and the test harness. The C++ trickery is used for
simulations.

--
Ian Collins

William Pursell

unread,
Oct 12, 2008, 3:18:05 AM10/12/08
to
On 10 Oct, 09:35, Richard Heathfield <r...@see.sig.invalid> wrote:

> Ian Collins said:
> > Some of us have good technical
> > reasons to compile some of our C with a C++ compiler.
>
> I've never heard a convincing reason for doing this - including P J
> Plauger's reason. But of course I respect your choice. And so, it appears,
> do implementers!
>

Here's one more reason (whether convincing or not, I don't know
but suspect you will find "not"). Choice and flexibility are
good things. I have seen run-time throughput of a program drop
as much as 10% merely by changing "-std=c89" to "-std=c99".
In all of the cases where this sort of thing happened, it
was easy enough to add more compiler flags to make the
performance difference negligible; my point is that I was
only able to perform those comparisons because the code
conformed to both standards. If I were so inclined, it
might prove interesting to compile the code as C++ and
compare the performance. If the code does not compile as
C++, then one can't even perform such an experiment.

Nick Keighley

unread,
Oct 12, 2008, 3:47:44 PM10/12/08
to
On Oct 10, 12:29 pm, Richard Heathfield <r...@see.sig.invalid> wrote:
> Ian Collins said:

<snip>

[using C++ to emulate hardware]

> Well, I certainly wouldn't do it that way. If I have understood you
> correctly, you're using one set of code for development, and a very
> different set of code (and indeed a different language!) for testing.
> Okay, I'm not going to say it was a bad decision, but it does go against
> what I would consider to be good test design principles.

I believe he's talking about using C++ to emulate hardware.
This means a large chunk of the software can be tested
without specialist hardware. And with superior debugging
facilities.

With really specialised hardware the hardware may not exist
when the software development starts.

Some peripherals may be expensive, power hungry physically large
or massive (I've worked with power amplifiers that filled a room).


--
Nick Keighley

Ian Collins

unread,
Oct 12, 2008, 4:17:32 PM10/12/08
to
In my case it was power supplies that can fill a room - with smoke if
you drive them incorrectly!

--
Ian Collins

David Thompson

unread,
Oct 13, 2008, 1:13:48 AM10/13/08
to
On Sat, 4 Oct 2008 19:13:48 +0100, "Malcolm McLean"
<regn...@btinternet.com> wrote:
<snip>
> Now one good question is why use C at all when C++ is a near as makes no
> difference a superset of it? However let's say that we decide that we want
> to discourage people from using object-orientation, because of certain
> drawbacks we see in the methodogy. A politically effective way of doing this
> is to ban C++.
>
> OK, so here's a fragment of our C program
>
> void encrypt(unsigned char *data, size_t len)
> {
> int i;
>
May be unsafe/wrong depending on range of size_t.

> for(i=0;i<len;i++)
> data ^= 0xCC;

Constraint violation. Presumably you meant data[i].
> }
>
> A few weeks later, the terrible news come through. Our encryption has been
> compromised. We need a beter method, and fast.
>
weeks? sci.crypt can do that for you in barely a minute or two.

> So we dust off our Sedgewick and realise that there is somethign called the
> RSA cryptosystem. This is very much better, and it is not too difficult to
> implment, as long as you have a huge integer library. Well we've got one,
> but it's in C++.
>
> No problem. Change the file extension to .cpp, and drop in
>
> void encrypt(unsigned char *data, size_t len)
> {
> bignum prime1(13);
> bignum prime2(17);
> bignum unfactorisable = prime1 * prime2;
>
Those numbers aren't nearly big enough to be secure. More to the
point, no numbers representable as integer literals (even long long)
on any likely implementation will be. Plus the 'naive' RSA encryption
primitive often shown in textbooks, just data up pubexpt mod modulus,
can be insecure in other ways. And even after you get a good design,
_coding_ secure crypto code in most environments requires techniques
not commonly used, or known, for ordinary code. So you are almost
always better off using an established crypto library, which are
available for both C and C++ among others, than writing your own.

In short, not a very good example for your case. <G>

> /* (etc) */
> }
>
> Now we're back in business. Nothing else needs to be changed. We've dropped
> in an emergency C++ bignum library and the code is now C++ and won't compile
> under C, but that is small price for turning out our improved encryption on
> time.

See above.
- formerly david.thompson1 || achar(64) || worldnet.att.net

Old Wolf

unread,
Oct 13, 2008, 9:14:29 PM10/13/08
to

And those reasons are?

Ian Collins

unread,
Oct 13, 2008, 10:24:39 PM10/13/08
to
If you read my responses elsewhere (my last couple of responses to
Richard H.) in this thread, you'll see.

--
Ian Collins

It is loading more messages.
0 new messages