473,395 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

C99 Question

Hi,

Which section of C99 says that return value
of malloc(3) should not be casted?

Thanks.

--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
Nov 14 '05
110 4357
"P.J. Plauger" wrote:
"CBFalconer" <cb********@yahoo.com> wrote in message
> Mr Zanvar should note that ERT, better known in these parts as
> Trollsdale, is usually wrong and gives (as in this case) bad
> advice.

Whatever his record, I happen to agree with him on this matter.


However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.


Believe what you want.


I shall :-) Prepare to be quoted by Trollsdale as authorative
confirmation for anything. He also revises quotes.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #51
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?
Good question! The ANSI/ISO C 99 standard does *not* say that
the return value of malloc should not be casted.

I *always* cast malloc's return value

char* p = (char*)malloc(n*sizeof(char));

so that my C++ compiler won't complain.


The best way to keep your C++ compiler from complaining is to avoid
feeding it C code.
There is *no* advantage to omitting the cast.
It is purely a style issue
but some C programmers have become fond of this style
and invented various *lame* arguments
to justify their personal aesthetics.


Nonsense, as usual.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #52
"P.J. Plauger" <pj*@dinkumware.com> writes:
"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:bs*************@news.t-online.com...
I consider people who compile C code with a C++ compiler to be quite at
the newbie end of the spectrum.


You make me feel young again.


I think you've answered this before, but I don't remember the details,
I'm too lazy to do a search, and it probably couldn't hurt to repeat
it here.

Why do you want to compile C code with a C++ compiler?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #53
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"P.J. Plauger" <pj*@dinkumware.com> writes:
"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:bs*************@news.t-online.com...
I consider people who compile C code with a C++ compiler to be quite at the newbie end of the spectrum.
You make me feel young again.


I think you've answered this before, but I don't remember the details,
I'm too lazy to do a search, and it probably couldn't hurt to repeat
it here.


I'm almost too lazy to answer, but since it's New Year's Eve and
I'm having trouble starting another project...
Why do you want to compile C code with a C++ compiler?


Actually, I want to compile our C code with *all* significant C and C++
compilers.

For one thing, the C++ Standard is intentionally silent (thanks to me)
on whether the C library has "C" or "C++" linkage. We have some OEM
customers who want the C names mangled, to provide link-time argument
type checking, and we have many others who want C names to look like,
well, C names.

For another thing, C++ is indeed in some ways a "better C", as
Stroustrup has been asserting for the past decade and a half. We
find bugs in hoary C code quite often when compiling it as C. So
it's just part of our shop discipline to make sure all our C code
compiles as C++ too.

I agree that you have to write more casts in C++ than in C, and
I agree that casts can sometimes disguise other problems. But it's
been my experience over the past ten years that casts tend to hide
stupid bugs, which are relatively easy to find, while compiling as
C++ tends to find subtler bugs, which are not. The tradeoff has
been well worth it for us.

HTH,

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #54
begin followup to Keith Thompson:
Why do you want to compile C code with a C++ compiler?


The obvious recursive answer: To catch the problem of missing

#include <stdlib.h>

even if the return value of every malloc is casted...

Seriously, the subset of C that also compiles as C++ is a nice,
simple language. A and C++ compiler will emit a clear error where
naked C will just warn about seemingly obscure stuff.

$ cat a.c
int main() {
int print_a_double(int);
return print_a_double(1);
}

$ cat b.c
#include <stdio.h>
void print_a_double(double x) { printf("%g\n", x); }

$ gcc -Wall a.c b.c && ./a.out
5.04822

Oops. Evil. Incarnate.

$ g++ a.c b.c
/tmp/ccvpYiSi.o(.text+0x16): In function `main':
: undefined reference to `print_a_double(int)'
collect2: ld returned 1 exit status

So even on outright misleading prototype is caught by C++,
though only in the linking phase. The more realistic case of

extern print_a_double();

instead of

int print_a_double(int);

won't even compile with C++.

--
Für Google, Tux und GPL!
Nov 14 '05 #55
Richard Heathfield wrote:
C and C++ are different languages.

In C++, you'd be better off doing this:

char *p = new char[n];

unless you wanted to resize the string at some point
in which case you'd be better off using a std::string. cat richard.c #include <stdio.h>

int richard(size_t n) {
char *p = new char[n];
return n;
}
gcc -Wall -std=c99 -pedantic -c richard.c

richard.c: In function `richard':
richard.c:4: `new' undeclared (first use in this function)
richard.c:4: (Each undeclared identifier is reported only once
richard.c:4: for each function it appears in.)
richard.c:4: parse error before "char"
richard.c:4: warning: unused variable `p'
The problem is that I can't get my C compiler to accept this.

Are you suggesting that
I should write and maintain two separate versions of function richard?
Just so that I can use one with C and the other with C++ programs?
Do you do that?
And, if so, does your employer/client know that you do that?

I think that most (at least my) employers/clients would prefer that
I would develop and maintain for a single version
which both C and C++ compilers could compile.

Nov 14 '05 #56
E. Robert Tisdale wrote:
Richard Heathfield wrote:
C and C++ are different languages.

In C++, you'd be better off doing this:

char *p = new char[n];

unless you wanted to resize the string at some point
in which case you'd be better off using a std::string.


> cat richard.c

#include <stdio.h>

int richard(size_t n) {
char *p = new char[n];
return n;
}
> gcc -Wall -std=c99 -pedantic -c richard.c

richard.c: In function `richard':
richard.c:4: `new' undeclared (first use in this function)
richard.c:4: (Each undeclared identifier is reported only once
richard.c:4: for each function it appears in.)
richard.c:4: parse error before "char"
richard.c:4: warning: unused variable `p'
The problem is that I can't get my C compiler to accept this.

Are you suggesting that
I should write and maintain two separate versions of function richard?
Just so that I can use one with C and the other with C++ programs?
Do you do that?
And, if so, does your employer/client know that you do that?

I think that most (at least my) employers/clients would prefer that
I would develop and maintain for a single version
which both C and C++ compilers could compile.


Why stop there? Why not make it valid Pascal, Perl, Java, Basic, and
Lisp also? Does your employer know that your code will have to be
completely rewritten when they decide they want to compile it as a Java
program?

Sometimes I write C and sometimes I write C++. I even write some
libraries that are usable in both. It's stupid, in my opinion to write
in the common subset of C and C++ without a very good reason. Plauger
seems to have a good reason to do so. Most people don't. Do you?

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #57
Kevin Goodsell wrote:
Sometimes I write C and sometimes I write C++.
I even write some libraries that are usable in both.
Do *you* have good reasons for doing so?
It's stupid, in my opinion to write in the common subset of C and C++
without a very good reason.
Plauger seems to have a good reason to do so.
Most people don't.
How could you know that?
Do you?


My reasons are the same as Plauger's.
Nov 14 '05 #58
In article <3F**************@jpl.nasa.gov>, E.**************@jpl.nasa.gov
says...
My reasons are the same as Plauger's.


Gee, that was predictable.

--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #59
E. Robert Tisdale wrote:
Richard Heathfield wrote:
C and C++ are different languages.

In C++, you'd be better off doing this:

char *p = new char[n];
<snip>
The problem is that I can't get my C compiler to accept this.
I imagine your Pascal compiler has trouble with the malloc call you showed
us, too. So what?
Are you suggesting that
I should write and maintain two separate versions of function richard?
Not at all.
Just so that I can use one with C and the other with C++ programs?
Do you do that?
No, I'm suggesting that, if you wish to use C code in a C++ program, you can
generally do it without recompiling the C code.
And, if so, does your employer/client know that you do that?

I think that most (at least my) employers/clients would prefer that
I would develop and maintain for a single version
which both C and C++ compilers could compile.


Presumably they would also prefer for your single version to compile under
Pascal, Fortran, and COBOL too. Does it?

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #60
E. Robert Tisdale wrote:
Kevin Goodsell wrote:
Sometimes I write C and sometimes I write C++.
I even write some libraries that are usable in both.
Do *you* have good reasons for doing so?


I'm not him, but yes I do. I write C programs for preference, but
occasionally use C++ for RAD of GUI programs. I don't see why I should
foresake the use of my familiar C libraries when writing C++ programs. But
I don't see why I should rewrite my C code to be C++-compilable either. So
I simply call my C code from my C++ code. It works fine.
It's stupid, in my opinion to write in the common subset of C and C++
without a very good reason.
Plauger seems to have a good reason to do so.
Most people don't.


How could you know that?


Because, believe it or not, most people aren't in the business of writing
libc implementations for which they ship the source.
Do you?


My reasons are the same as Plauger's.


I'm afraid I find that very hard to believe, unless NASA has given up on
space altogether and decided to focus on the software tools development
side of things instead.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #61
Richard Heathfield wrote:
I'm suggesting that, if you wish to use C code in a C++ program,
you can generally do it without recompiling the C code.


Really! Are you an expert in C/C++ interoperability now?

Tell us how you would do it
without compiling the C code with a C++ compiler.
Is your method guaranteed to work?

Nov 14 '05 #62
Richard Heathfield wrote:
I write C programs for preference
but occasionally use C++ for RAD of GUI programs.
I don't see why I should forsake the use of my familiar C libraries
when writing C++ programs.
Who said that you should?
But I don't see why I should rewrite my C code
to be C++-compilable either.
Who said that you should?
So I simply call my C code from my C++ code. It works fine.


Please cite and quote the passage from the ANSI/ISO C++ standard
that *guarantees* that "it works fine".

C functions compiled by one compiler need not be callable
from programs compiled with any other compiler --
not even another C compiler.
The only way to guarantee that you can call C functions
from a C++ program is to compile them with the *same* C++ compiler.

Nov 14 '05 #63
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
[snip]
The problem is that I can't get my C compiler to accept this.

Are you suggesting that
I should write and maintain two separate versions of function richard?
Just so that I can use one with C and the other with C++ programs?


<OT> extern "C" </OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #64
E. Robert Tisdale wrote:
Richard Heathfield wrote:
I'm suggesting that, if you wish to use C code in a C++ program,
you can generally do it without recompiling the C code.
Really! Are you an expert in C/C++ interoperability now?

Tell us how you would do it
without compiling the C code with a C++ compiler.


extern "C" {
#include "mychdr.h"
};

and link the appropriate object file.
Is your method guaranteed to work?


No; it is possible to generate pathological examples which won't work. This
has not caused me the slightest difficulty in the Real World.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #65
E. Robert Tisdale wrote:
The only way to guarantee that you can call C functions
from a C++ program is to compile them with the *same* C++ compiler.


That is no guarantee, since not all C functions *can* be compiled by a C++
compiler.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #66
Martin Dickopp wrote:
I consider people who compile C code with a C++ compiler to be quite at
the newbie end of the spectrum.


Why? I'd be truly interested to know.

Best regards,

Sidney

Nov 14 '05 #67
CBFalconer wrote:
Whatever his record, I happen to agree with him on this matter.
However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.


This is intentionally phrased in a very negative way, of course. Putting
aside the negative connotations, what's wrong in wanting or needing this?

Best regards,

Sidney

Nov 14 '05 #68
begin followup to Sidney Cadot:
Martin Dickopp wrote:
I consider people who compile C code with a C++ compiler to
be quite at the newbie end of the spectrum.


Why? I'd be truly interested to know.


Most IDEs use file extension alone to chose C or C++ compilation.
And since the default extension for new files is typically .cpp,
a lot of newbies end up feeding their supposed C code to a C++
implementation.

Sometimes it's hard to distinguish the clueless from the paranoid.

--
Für Google, Tux und GPL!
Nov 14 '05 #69
Clark Cox wrote:
[snip...]
Pick a language. Either write C or write C++. If you're writing C++,
then use new (and don't cast), if you're writing C, then use malloc (and
don't cast). If, you are writing C, but trying to feed it to a C++
compiler, then why not just write C++, and be through with it?


The alternative you suggest is often simply not possible. For example,
my current project involves a library that needs to link to Matlab and
IDL, which cannot reliably be made to work with C++ compiled code - they
only support C plugins.

As to the point about compiling C code with a C++ compiler. While it is
certainly arguable that the merits of feeding C code to a C++ are
dubious, one has to bear in mind that it is almost a free ride. Most
properly written C code compiles flawlessly in C++, except for a very
small number of cases. Lack of malloc() result casting is by far the
most prominent cause for failure you would normally encounter. Given the
widely shared belief that it is a good thing to throw your code at as
many compilers as you can get your hands on to improve portability, and
maximize the number of warnings you get, I personally think it is worth it.

Then there's the second point I made a couple of times, that I consider
it also proper in terms of elegance: the result of a
"malloc(1000*sizeof(double))" is properly thought of as double*, and
it's only the fact that malloc() must be a general function that forces
it to return a void*. Casting it to its proper type (double *) restores
this obvious anomaly - I think it's proper to do this ASAP.

Now I'm not advocating that we go through all this once again, but I
always get a bit vexed when I see the zealous feeding frenzy that ensues
when anyone dares to mention the malloc casting issue.

Often times, the people telling me to stop compiling my C code with a
C++ compilers ("better download a good lint that will do equally well or
better" - a good point in itself), all of the sudden toss out the stale
"you may fail to notice that you didn't include stdlib.h" when arguing
the malloc cast issue. To them I say:

- make up your mind as to whether you are discussing C89 or C99.
- download a lint, or a free compiler that helps you detect this.
If you use a compiler that doesn't complain on prototype
omission, you have more pressing issues to worry about.
- failure to use strict warning flags in your compiler (just about
the only way you can get hurt by malloc casting nowadays) is a
much more serious software engineering practice mistake than
casting a malloc() result could ever be, even if you don't accept
the advantages.

I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.
Best regards, Sidney

Nov 14 '05 #70
Alexander Bartolich wrote:
begin followup to Sidney Cadot:
Martin Dickopp wrote:
I consider people who compile C code with a C++ compiler to
be quite at the newbie end of the spectrum.
Why? I'd be truly interested to know.


Most IDEs use file extension alone to chose C or C++ compilation.
And since the default extension for new files is typically .cpp,
a lot of newbies end up feeding their supposed C code to a C++
implementation.


Well I guess everybody here would agree that people who do this without
even being aware of it are rather clueless.

However, I'd hope to get a slightly more provoking answer from Martin
himself :-)
Sometimes it's hard to distinguish the clueless from the paranoid.


I don't think it's hard at all, actually. Just ask why they're doing it.
If they fail to understand the question, it's settled :-) If they give
some arguments that hold some ground, they're of the paranoid persuasion
(although, belonging in the latter category, I'd prefer 'cautious'
myself ;-)). The interesting part in that case lies in the reaction of
the asker. If he dismiss the argument out of hand, the discussion is for
all practical purposes over. Otherwise, both parties may learn a bit.

Best regards,
Sidney

Nov 14 '05 #71
Sidney Cadot wrote:
CBFalconer wrote:
Whatever his record, I happen to agree with him on this matter.

However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.


This is intentionally phrased in a very negative way, of course.
Putting aside the negative connotations, what's wrong in wanting
or needing this?


Why do you consider it negative (serious question)? I
deliberately used the "I believe" phrase in order to specify
possible misconceptions on my part. There is nothing wrong in
wanting or needing "this", it is simply (I believe) a desirable
attribute for his product.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #72
CBFalconer wrote:
Whatever his record, I happen to agree with him on this matter.
However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.
This is intentionally phrased in a very negative way, of course.
Putting aside the negative connotations, what's wrong in wanting
or needing this?

Why do you consider it negative (serious question)?
Because of the negative wording ('unwashed idiots', 'handholding').

Personally, I don't see much wrong (from the 'customer' perspective) in
the requirement that I want to recompile the delivered code using either
a C or C++ compiler. I don't presume one would have to be particularly
lacking in the personal hygiene-department, much less be an idiot, to
want this.
I deliberately used the "I believe" phrase in order to specify
possible misconceptions on my part. There is nothing wrong in
wanting or needing "this", it is simply (I believe) a desirable
attribute for his product.


Okay. Then we probably agree that Mr. Plauger at least has a valid
reason for wanting to compile C code using a C++ compiler.

Best regards,

Sidney

Nov 14 '05 #73
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:
... Most properly written C code compiles flawlessly in C++,
except for a very small number of cases.
Either you have a different definition of "properly written" than
I do, or your experience differs quite a bit from mine. Using
gcc's "-x c++" to compile .c files as C++ code, I find that *most*
of the (C) code I deal with fails to compile -- yet, in most cases, it
seems "properly written" to me.
Lack of malloc() result casting is by far the most prominent
cause for failure you would normally encounter.
This is just one of many errors that turns up. But the diagnosed
errors are not the ones that really worry me. The scariest are
the silent changes in semantics:

% cat t.c
#include <stdio.h>

struct A { char x[10]; };
int main(void) {
struct B { struct A { int i; } b1, b2; };

printf("sizeof(struct A) = %lu\n", (unsigned long)sizeof(struct A));
return 0;
}
% cc -O -Wall -ansi -pedantic -o t t.c
% ./t
sizeof(struct A) = 4
% cc -x c++ -O -Wall -ansi -pedantic -o t t.c
% ./t
sizeof(struct A) = 10
%

(The above is just a boiled-down example, but we have had code like
it. The problem turned up when someone wanted to link C++ code
against an existing C library.)
I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.


Well, C99 does obviate the "omit the cast to obtain a diagnostic
if you somehow forgot <stdlib.h>" argument. But if you are using
C99, you might start using some of the new C++ features, which are
not exactly compatible with C++. C99's bool and complex types are
different, its new "restrict" keyword does not exist in C++, its
anonymous aggregate constructor syntax means something new, and so
on.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #74
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:
Clark Cox wrote:
[snip...]
Pick a language. Either write C or write C++. If you're writing C++,
then use new (and don't cast), if you're writing C, then use malloc
(and don't cast). If, you are writing C, but trying to feed it to a
C++ compiler, then why not just write C++, and be through with it?

The alternative you suggest is often simply not possible. For example,
my current project involves a library that needs to link to Matlab and
IDL, which cannot reliably be made to work with C++ compiled code - they
only support C plugins.
That's exactly what 'extern "C"' is for.
As to the point about compiling C code with a C++ compiler. While it is
certainly arguable that the merits of feeding C code to a C++ are
dubious, one has to bear in mind that it is almost a free ride. Most
properly written C code compiles flawlessly in C++, except for a very
small number of cases. Lack of malloc() result casting is by far the
most prominent cause for failure you would normally encounter. Given the
widely shared belief that it is a good thing to throw your code at as
many compilers as you can get your hands on to improve portability, and
maximize the number of warnings you get, I personally think it is worth it.

Then there's the second point I made a couple of times, that I consider
it also proper in terms of elegance: the result of a
"malloc(1000*sizeof(double))" is properly thought of as double*, and
it's only the fact that malloc() must be a general function that forces
it to return a void*. Casting it to its proper type (double *) restores
this obvious anomaly - I think it's proper to do this ASAP.
Of course, seeing as void* automatically converts to any other
pointer type, there is no need for the cast. The simple fact that you
always assign the result of malloc to some variable (in any non-trivial
program), and that variable (hopefully) is of the proper type, the cast
is completely superfluous. Most of the potential dangers have been
closed with the removal of implicit int in C99, so it is no longer such
a dangeous thing to do, but it is still a useless thing to do.

When I'm reviewing code, casting, in general, is a sign that
something out of the ordinary is going on.
Now I'm not advocating that we go through all this once again, but I
always get a bit vexed when I see the zealous feeding frenzy that ensues
when anyone dares to mention the malloc casting issue.

Often times, the people telling me to stop compiling my C code with a
C++ compilers ("better download a good lint that will do equally well or
better" - a good point in itself), all of the sudden toss out the stale
"you may fail to notice that you didn't include stdlib.h" when arguing
the malloc cast issue. To them I say:

- make up your mind as to whether you are discussing C89 or C99.
- download a lint, or a free compiler that helps you detect this.
If you use a compiler that doesn't complain on prototype
omission, you have more pressing issues to worry about.
- failure to use strict warning flags in your compiler (just about
the only way you can get hurt by malloc casting nowadays) is a
much more serious software engineering practice mistake than
casting a malloc() result could ever be, even if you don't accept
the advantages.

I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.


Yes, with C99, there isn't much reason *not to* cast, but there is
still no reason *to* cast. And, if both doing something and not doing
something are equally meaningless, then I it makes logical sense to opt
for the "not doing something" choice.

Nov 14 '05 #75
Clark Cox wrote:
The alternative you suggest is often simply not possible. For example,
my current project involves a library that needs to link to Matlab and
IDL, which cannot reliably be made to work with C++ compiled code - they
only support C plugins.
That's exactly what 'extern "C"' is for.
extern "C" is for letting a C++ compiler use C-type linkage, allowing
use of a C library from within C++ (but /not/ the other way round, which
would be needed for your suggestion to work).
[snip]
Then there's the second point I made a couple of times, that I consider
it also proper in terms of elegance: the result of a
"malloc(1000*sizeof(double))" is properly thought of as double*, and
it's only the fact that malloc() must be a general function that forces
it to return a void*. Casting it to its proper type (double *) restores
this obvious anomaly - I think it's proper to do this ASAP.


Of course, seeing as void* automatically converts to any other
pointer type, there is no need for the cast.


It does only do so on assignment, passing as a known-type parameter, and
perhaps a couple of other situations. You implicitly depend on any of
these things being done to the malloc() result, in order to have it
converted to its proper type. This is of course true in the vast
majority of cases.

Last time this came up I showed the following possible bug:

int *x = malloc(1000*sizeof(double));

.... not casting the malloc ASAP here makes the bug go unnoticed, i.e.,

int *x = (double *)malloc(1000*sizeof(double));

Would trigger a compile-time error.

Several responses were made then. The first one was "I don't see this
happen in practice" - which is dodging the issue.

Another one was, that this should properly be written as:

int *x = malloc(1000*sizeof *x);

....That's one way of avoiding the problem. However, what to in this case:

#define N 1000

int *fill(int *x, int n, int value)
{
int i;

if (!x)
exit(EXIT_FAILURE);

for(i=0;i<n;i++) x[i]=value;

return x;
}

void do_something_clever(int *x, int n)
{
/*......*/
}

int main(void)
{
/* no way to get the sizeof of a formal parameter's base type.
* resort to giving the base type literally... */

do_something_clever(fill(malloc(N*sizeof(double), N, -1), N);

/*...*/
return 0;
}

Sure, this is not the world's most elegant code, but, in principle,
there's nothing wrong with it - other than the bug of course.

The point here is that relying on conversion-by-assignment for a
malloc() result is something that cannot be relied upon for 100% of
cases. It just happens to be the malloc() usage pattern in 99.99% of cases.
The simple fact that you always assign the result of malloc to
some variable (in any non-trivial program),
Yes. That's an implicit dependence on a usage pattern, which is rarely
spelled out when the 'rule' is stated.
and that variable (hopefully) is of the proper type, the cast
is completely superfluous.
From a pragmatic standpoint, I agree. But I disagree on a more
fundamental level.
Most of the potential dangers have been
closed with the removal of implicit int in C99, so it is no longer such
a dangeous thing to do, but it is still a useless thing to do.

When I'm reviewing code, casting, in general, is a sign that
something out of the ordinary is going on.
I agree, but then I think that correcting the compiler's idea of a type
of a memory block qualifies.

I'm not trying to persuade you at all. What I am saying is that it is
not a completely black-or-white thing. A case can be made for the cast,
although you are free to think it's a very weak case of course.
I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.

Yes, with C99, there isn't much reason *not to* cast, but there is
still no reason *to* cast.
With C99 and any modern C89 compiler.
And, if both doing something and not doing
something are equally meaningless, then I it makes logical sense to opt
for the "not doing something" choice.


Unless (as I do) I want to compile the C code with a C++ compiler as
well. Most here will find this a bad reason though, and that's fine by me.

Best regards,

Sidney
Nov 14 '05 #76
Chris Torek wrote:
... Most properly written C code compiles flawlessly in C++,
except for a very small number of cases.
Either you have a different definition of "properly written" than
I do, or your experience differs quite a bit from mine. Using
gcc's "-x c++" to compile .c files as C++ code, I find that *most*
of the (C) code I deal with fails to compile -- yet, in most cases, it
seems "properly written" to me.
In your experience, what are the most important reasons for this to fail?
Lack of malloc() result casting is by far the most prominent
cause for failure you would normally encounter. This is just one of many errors that turns up.
But the diagnosed errors are not the ones that really worry me.
The scariest are the silent changes in semantics:
Certainly.
% cat t.c
#include <stdio.h>

struct A { char x[10]; };
int main(void) {
struct B { struct A { int i; } b1, b2; };

printf("sizeof(struct A) = %lu\n", (unsigned long)sizeof(struct A));
return 0;
}
% cc -O -Wall -ansi -pedantic -o t t.c
% ./t
sizeof(struct A) = 4
% cc -x c++ -O -Wall -ansi -pedantic -o t t.c
% ./t
sizeof(struct A) = 10
%
Ouch, that's messy.

In all objectivity though: wouldn't you agree that most C programmers
(even moderately able ones) would expect sizeof(struct A) to refer to
the first definition? I know I would.

To me, this example says: C has some pretty non-intuitive rules with
regard to type resolution; avoid shadowing type names to avoid confusion.

When I compile a C program as C++, I make a habit of also testing the
resulting executable (the fact that one can do this is an advantage
compared to lint). I would expect all my code to work in C++ as it does
in C. If this fails for some reason, I am bound to learn something from it.

In other words, I tend to constrain myself to the very large subset of C
that's also C++ (which is surprisingly easy). Extra constraints are a
good thing: that's why I prefer typed languages, am happy with C
prototypes, and use very strict warning flags. In my limited experience,
the C/C++-intersection language I use does not impose many strange
demands on my C coding style (the malloc-cast, in practice, is the only
one that I am consciously aware of), and it gives some benefits. The
mileage of most here does seem to be worse than mine, although I suspect
that some haven't even done the test drive :-)
(The above is just a boiled-down example, but we have had code like
it. The problem turned up when someone wanted to link C++ code
against an existing C library.)
You must be glad you cought it. It's a nasty one.... It does not even
qualify as a bug in C (it has perfectly well-defined semantics), but
still it is best to avoid this type of thing altogether, I would say.

Now for one question that I hesitate to ask: would you have cought this
issue earlier on in your development cycle if you had done a C++ test
compile & run every couple of weeks or so? (Perhaps that's not possible
because your code is too "non-C++" for that to be an option).

I prefer to do that once in a while on a Friday afternoon; the number of
(potential) problems I catch in that way is small, but also non-zero.
I guess what I am trying to say is that the issue is not as clear-cut as
many here make it out to be. It sometimes looks like rehashing of
arguments that were only relevant ten years ago.

Well, C99 does obviate the "omit the cast to obtain a diagnostic
if you somehow forgot <stdlib.h>" argument. But if you are using
C99, you might start using some of the new C++ features, which are
not exactly compatible with C++. C99's bool and complex types are
different, its new "restrict" keyword does not exist in C++, its
anonymous aggregate constructor syntax means something new, and so
on.


Yes, there will be some divergence (although I suppose C++ compilers
will start to support "restrict" sooner or later). For me, it's quite
simple: as long as the benefits of having the ability to compile C
programs with C++ programs outweigh the disadvantages, I'll keep on
doing it. For now, it's a small enough price to pay (IMHO).

Best regards,

Sidney

Nov 14 '05 #77
in comp.lang.c i read:
When I compile a C program as C++, I make a habit of also testing the
resulting executable (the fact that one can do this is an advantage
compared to lint). I would expect all my code to work in C++ as it
does in C. If this fails for some reason, I am bound to learn
something from it.


once you find the issue. as chris showed there were no compiler detected
errors, and you can easily see how that sort of thing might only be found
later when trying to diagnose odd results -- thus depends entirely on the
quality of the test suite. further the `problem' only exists when using an
executable compiled with the `wrong' compiler, the program works as
expected otherwise.

--
a signature
Nov 14 '05 #78
those who know me have no need of my name wrote:
in comp.lang.c i read:

When I compile a C program as C++, I make a habit of also testing the
resulting executable (the fact that one can do this is an advantage
compared to lint). I would expect all my code to work in C++ as it
does in C. If this fails for some reason, I am bound to learn
something from it.
once you find the issue. as chris showed there were no compiler detected
errors, and you can easily see how that sort of thing might only be found
later when trying to diagnose odd results -- thus depends entirely on the
quality of the test suite. further the `problem' only exists when using an
executable compiled with the `wrong' compiler, the program works as
expected otherwise.


Well, that is all true. I'm not sure I get your point though.

Best regards,

Sidney

Nov 14 '05 #79
In article <bt**********@news.tudelft.nl>, si****@jigsaw.nl says...
Yes, there will be some divergence (although I suppose C++ compilers
will start to support "restrict" sooner or later).


I'm not sure about that, even Stroustrup himself admits that C99
and C++ are siblings, I.e. no parent/child relationship at all.
--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #80
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:
Clark Cox wrote:
The alternative you suggest is often simply not possible. For example,
my current project involves a library that needs to link to Matlab and
IDL, which cannot reliably be made to work with C++ compiled code - they
only support C plugins.

That's exactly what 'extern "C"' is for.


extern "C" is for letting a C++ compiler use C-type linkage, allowing
use of a C library from within C++ (but /not/ the other way round, which
would be needed for your suggestion to work).


[mildly-OT]
extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):

//C++ code in file file1.cpp:
extern "C"
{
int foo(int i)
{
return i+1;
}
}

/*C code in file file2.c:*/
#include <stdio.h>

extern int foo(int);

int main()
{
printf("%d\n", foo(1));
return 0;
}
[/mildly-OT]

Nov 14 '05 #81
[in <news:bt**********@news.tude lft.nl>, Sidney Cadot wrote:]
... Most properly written C code compiles flawlessly in C++,
except for a very small number of cases.
Chris Torek wrote:
Either you have a different definition of "properly written" than
I do, or your experience differs quite a bit from mine. Using
gcc's "-x c++" to compile .c files as C++ code, I find that *most*
of the (C) code I deal with fails to compile -- yet, in most cases, it
seems "properly written" to me.

In article <bt**********@news.tudelft.nl>
Sidney Cadot <si****@jigsaw.nl> writes:In your experience, what are the most important reasons for this to fail?
I do not know about "most important", and it is not something I
do often, but here is another trivial example of code that compiles
as C but not as C++. One might use something like this as a
"patchable constant" for ROMs, for embedded-system code:

% cat t1.c
const int n = 3;
% cat t2.c
#include <stdio.h>

extern const int n;

int main(void) {
printf("n = %d\n", n);
return 0;
}
% cc -o t t[12].c && ./t
n = 3
% cc -x c++ -o t t[12].c && ./t
/tmp/ccmoKUzh.o: In function `main':
/tmp/ccmoKUzh.o(.text+0xa): undefined reference to `n'

Another problem that comes up, albeit rarely, is the change in
sizeof 'a' (1 in C++, sizeof(int) in C). This one, like my earlier
example, usually results in silent breakage instead of compile-time
failure.
[scope rules example]

Ouch, that's messy.
Indeed.
In all objectivity though: wouldn't you agree that most C programmers
(even moderately able ones) would expect sizeof(struct A) to refer to
the first definition? I know I would.
I am not sure whether I would say that -- it is hard to tell without
actually doing a statistical sample. :-)
To me, this example says: C has some pretty non-intuitive rules with
regard to type resolution; avoid shadowing type names to avoid confusion.
This *is* a good rule.
Now for one question that I hesitate to ask: would you have cought this
issue earlier on in your development cycle if you had done a C++ test
compile & run every couple of weeks or so? (Perhaps that's not possible
because your code is too "non-C++" for that to be an option).


The code was never intended to be used with C++, and in fact, the
bones of it were written either before cfront existed, or -- at
the latest -- when C++ was "whatever cfront accepts". But in the
late 1990s, someone decided they wanted to import some of it into
a C++ program and, well. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #82
Chris Torek <no****@torek.net> wrote in message news:<bt********@enews3.newsguy.com>...
[in <news:bt**********@news.tude lft.nl>, Sidney Cadot wrote:]
... Most properly written C code compiles flawlessly in C++,
except for a very small number of cases.
Chris Torek wrote: Either you have a different definition of "properly written" than
I do, or your experience differs quite a bit from mine. Using
gcc's "-x c++" to compile .c files as C++ code, I find that *most*
of the (C) code I deal with fails to compile -- yet, in most cases, it
seems "properly written" to me.
In article <bt**********@news.tudelft.nl>
Sidney Cadot <si****@jigsaw.nl> writes:
In your experience, what are the most important reasons for this to fail?
I do not know about "most important", and it is not something I
do often, but here is another trivial example of code that compiles
as C but not as C++. One might use something like this as a
"patchable constant" for ROMs, for embedded-system code:

% cat t1.c
const int n = 3;
% cat t2.c
#include <stdio.h>

extern const int n;

int main(void) {
printf("n = %d\n", n);
return 0;
}
% cc -o t t[12].c && ./t
n = 3
% cc -x c++ -o t t[12].c && ./t
/tmp/ccmoKUzh.o: In function `main':
/tmp/ccmoKUzh.o(.text+0xa): undefined reference to `n'


As in so many other cases, you get the identical result in C and C++
by adding a bit of information. In this case, adding an "extern" in
t1.c to tell C++ that "n" can be used elsewhere solves the problem.
Another problem that comes up, albeit rarely, is the change in
sizeof 'a' (1 in C++, sizeof(int) in C). This one, like my earlier
example, usually results in silent breakage instead of compile-time
failure.
[scope rules example]

Ouch, that's messy.


Indeed.
In all objectivity though: wouldn't you agree that most C programmers
(even moderately able ones) would expect sizeof(struct A) to refer to
the first definition? I know I would.


I am not sure whether I would say that -- it is hard to tell without
actually doing a statistical sample. :-)
To me, this example says: C has some pretty non-intuitive rules with
regard to type resolution; avoid shadowing type names to avoid confusion.


This *is* a good rule.
Now for one question that I hesitate to ask: would you have cought this
issue earlier on in your development cycle if you had done a C++ test
compile & run every couple of weeks or so? (Perhaps that's not possible
because your code is too "non-C++" for that to be an option).


The code was never intended to be used with C++, and in fact, the
bones of it were written either before cfront existed, or -- at
the latest -- when C++ was "whatever cfront accepts". But in the
late 1990s, someone decided they wanted to import some of it into
a C++ program and, well. :-)


I, at least, never defined C++ as "whet Cfront accepted".

- Bjarne Stroustrup; http://www.research.att.com/~bs
Nov 14 '05 #83
Clark Cox wrote:
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:

Clark Cox wrote:
extern "C" is for letting a C++ compiler use C-type linkage, allowing
use of a C library from within C++ (but /not/ the other way round, which
would be needed for your suggestion to work).

extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):


The fact that it happens to work on some compiler suites (gcc, for
example) doesn't help much. My library needs to work on AIX, SGI, HP-UX,
Solaris, an some more, with their various proprietary compiler suites.

7.5 of the C++ standard states:

"9. Linkage from C++ to objects defined in other languages and to
objects defined in C++ from other languages is implementation-defined
and language-dependent. Only where the object layout strategies of two
language implementations are similar enough can such linkage be achieved."

This effectively disqualifies C++ as an implementation language for my
project, since we have to link to IDL/Matlab (both written in C) on all
these platforms.
Best regards,

Sidney

Nov 14 '05 #84
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:
Clark Cox wrote:
In article <bt**********@news.tudelft.nl>,
Sidney Cadot <si****@jigsaw.nl> wrote:

Clark Cox wrote:
extern "C" is for letting a C++ compiler use C-type linkage, allowing
use of a C library from within C++ (but /not/ the other way round, which
would be needed for your suggestion to work).

extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):


The fact that it happens to work on some compiler suites (gcc, for
example) doesn't help much. My library needs to work on AIX, SGI, HP-UX,
Solaris, an some more, with their various proprietary compiler suites.

7.5 of the C++ standard states:

"9. Linkage from C++ to objects defined in other languages and to
objects defined in C++ from other languages is implementation-defined
and language-dependent. Only where the object layout strategies of two
language implementations are similar enough can such linkage be achieved."

This effectively disqualifies C++ as an implementation language for my
project, since we have to link to IDL/Matlab (both written in C) on all
these platforms.


extern "C" is by defintion implementation defined in either
direction, but where it works, it works in both directions. Extern "C"
tells the C++ compiler to use C calling and naming conventions, whether
you are applying it to a function whose implementation is in C, or a
function whose implementation is in C++.
Check out the comp.lang.c++ FAQ:
http://www.parashift.com/c++-faq-lit...c-and-cpp.html

Pay attention to question 32.6 "How can I create a C++ function
f(int,char,float) that is callable by my C code?"

Nov 14 '05 #85
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bt**********@news.tudelft.nl...
extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):


The fact that it happens to work on some compiler suites (gcc, for
example) doesn't help much. My library needs to work on AIX, SGI, HP-UX,
Solaris, an some more, with their various proprietary compiler suites.

7.5 of the C++ standard states:

"9. Linkage from C++ to objects defined in other languages and to
objects defined in C++ from other languages is implementation-defined
and language-dependent. Only where the object layout strategies of two
language implementations are similar enough can such linkage be achieved."

This effectively disqualifies C++ as an implementation language for my
project, since we have to link to IDL/Matlab (both written in C) on all
these platforms.


Every one of the platforms you list above has at least one combined
C/C++ compiler. If *any* such combo has linkage or layout problems
between their C and C++ personae, I don't know about it. And I'd be
astonished to encounter such problems.

You may contrive other reasons to disqualify C++ for your project,
but this particular one is terminally lame.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #86

On Sat, 3 Jan 2004, P.J. Plauger wrote:

"Sidney Cadot" <si****@jigsaw.nl> wrote...
extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):


The fact that it happens to work on some compiler suites (gcc, for
example) doesn't help much. My library needs to work on AIX, SGI, HP-UX,
Solaris, an some more, with their various proprietary compiler suites. [...] This effectively disqualifies C++ as an implementation language for my
project, since we have to link to IDL/Matlab (both written in C) on all
these platforms.


Every one of the platforms you list above has at least one combined
C/C++ compiler. If *any* such combo has linkage or layout problems
between their C and C++ personae, I don't know about it. And I'd be
astonished to encounter such problems.

You may contrive other reasons to disqualify C++ for your project,
but this particular one is terminally lame.


This may be terminally naive of me, and it's certainly off-topic,
but couldn't the problem be that those compilers that compile both C
and C++, do not produce object formats compatible with the object
formats supported by IDL/Matlab? Presumably Mr. Cadot does not
have either C or C++ source code for Matlab's libraries...

-Arthur
Nov 14 '05 #87
P.J. Plauger wrote:
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bt**********@news.tudelft.nl...

extern "C" *does* work in both directions (i.e. you can write C++
code that is callable from C code and vice versa):
The fact that it happens to work on some compiler suites (gcc, for
example) doesn't help much. My library needs to work on AIX, SGI, HP-UX,
Solaris, an some more, with their various proprietary compiler suites.

7.5 of the C++ standard states:

"9. Linkage from C++ to objects defined in other languages and to
objects defined in C++ from other languages is implementation-defined
and language-dependent. Only where the object layout strategies of two
language implementations are similar enough can such linkage be achieved."

This effectively disqualifies C++ as an implementation language for my
project, since we have to link to IDL/Matlab (both written in C) on all
these platforms.

Every one of the platforms you list above has at least one combined
C/C++ compiler. If *any* such combo has linkage or layout problems
between their C and C++ personae, I don't know about it. And I'd be
astonished to encounter such problems.

You may contrive other reasons to disqualify C++ for your project,
but this particular one is terminally lame.


I do not have regular access to all the platforms we have to support,
much less so to all platforms with all used versions of Matlab and IDL
(ranging from +/- 5 years old, to current). We distribute the library as
source code; the user (or his sysadmin) has to compile it. The
installation process /has/ to be as simple as configure/make/make install.

Using C++ would imply that

(1) I'd have to know the C compilers with which the particular versions
of Matlab/IDL on the user system was compiled, and act appropriately on
different combibations.

(2) The user would need to have the (possibly old) C/C++ compiler suite
on his system, in many cases.

(3) The old C/C++ compiler suite needs to support dynamic linking of
C++ code to binary-only libraries (that's how matlab and IDL work).

Implementing it in C++ would be a maintenance nightmare, bound to end in
many more disgruntled users (because they couldn't get the damn thing to
work) than we currently have. I'd be busier special-casing for weird
combinations than anything else - there'd be little time left to improve
the library functionality.

One further note is that both Matlab and IDL do not officially support
linking to C++ code (although, yes, it can be done, for newer versions,
if one is careful).

Due to all these real-life constraints, we opted for the conservative
approach by sticking to C. Some special-casing still needs to be done,
but this is along the dimension of Matlab/IDL versions (which change
APIs between versions now and then).

Frankly, I'm pleasantly surprised that it works for so many users
without a hitch, when using C, given the many combinations of Matlab/IDL
versions and OS'es our library works for.

Your calling this "contrived" reason "particularly lame" suggests to me
that I failed to make the context of the problems we faced not clear
enough. I hope this helps.

Best regards,

Sidney

Nov 14 '05 #88
Arthur J. O'Dwyer wrote:
Every one of the platforms you list above has at least one combined
C/C++ compiler. If *any* such combo has linkage or layout problems
between their C and C++ personae, I don't know about it. And I'd be
astonished to encounter such problems.

You may contrive other reasons to disqualify C++ for your project,
but this particular one is terminally lame.


This may be terminally naive of me, and it's certainly off-topic,
but couldn't the problem be that those compilers that compile both C
and C++, do not produce object formats compatible with the object
formats supported by IDL/Matlab? Presumably Mr. Cadot does not
have either C or C++ source code for Matlab's libraries...


I don't. Floating even farther off-topic, I work in a commercial setting
where we have a product to deliver. We cannot afford to have too many
unpleasant surprises; if the Matlab and IDL docs (and newsgroups)
consistently state that one should not attempt to write plugins using
C++, that's all there is to it as far as I am concerned.

Best regards,
Sidney

Nov 14 '05 #89
Clark Cox wrote:
Extern "C" tells the C++ compiler
to use C calling and naming conventions


No!
Extern "C" only *helps* with linkage.
There is *no* ANSI/ISO C++ interoperability standard
which governs function calling protocol.
Different compilers may pass and return values in different registers or
in different order on the program stack.
Built-in data types may have different sizes.

Nov 14 '05 #90
In article <3F**************@jpl.nasa.gov>,
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Clark Cox wrote:
Extern "C" tells the C++ compiler
to use C calling and naming conventions
No!
Extern "C" only *helps* with linkage.
There is *no* ANSI/ISO C++ interoperability standard
which governs function calling protocol.
Different compilers may pass and return values in different registers or
in different order on the program stack.
Built-in data types may have different sizes.


Which is why my first sentence, which you clipped, was:
extern "C" is by defintion implementation defined ...


Nov 14 '05 #91
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bt**********@news.tudelft.nl...
Your calling this "contrived" reason "particularly lame" suggests to me
that I failed to make the context of the problems we faced not clear
enough. I hope this helps.


Now that you've listed six pretty good reasons for not using C++
with your project, that does help me understand why you don't use
C++. I understand and respect your decision based on those reasons.
But that doesn't alter the lameness of the single reason you
originally cited.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #92
P.J. Plauger wrote:
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bt**********@news.tudelft.nl...

Your calling this "contrived" reason "particularly lame" suggests to me
that I failed to make the context of the problems we faced not clear
enough. I hope this helps.

Now that you've listed six pretty good reasons for not using C++
with your project, that does help me understand why you don't use
C++. I understand and respect your decision based on those reasons.
But that doesn't alter the lameness of the single reason you
originally cited.


The magic word is "context" I guess.

Best regards,

Sidney

Nov 14 '05 #93
Clark Cox wrote:
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Clark Cox wrote:
Extern "C" tells the C++ compiler
to use C calling and naming conventions


No!
Extern "C" only *helps* with linkage.
There is *no* ANSI/ISO C++ interoperability standard
which governs function calling protocol.
Different compilers may pass and return values in different
registers or in different order on the program stack.
Built-in data types may have different sizes.


Which is why my first sentence, which you clipped, was:
extern "C" is by defintion implementation defined ...


Trollsdale is famous for this sort of trick. He also revises
quotes without warning. Note his irrelevant referance to a stack,
in addition.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #94
CBFalconer <cb********@yahoo.com> writes:
Clark Cox wrote:
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Clark Cox wrote:

> Extern "C" tells the C++ compiler
> to use C calling and naming conventions

No!
Extern "C" only *helps* with linkage.
There is *no* ANSI/ISO C++ interoperability standard
which governs function calling protocol.
Different compilers may pass and return values in different
registers or in different order on the program stack.
Built-in data types may have different sizes.


Which is why my first sentence, which you clipped, was:
extern "C" is by defintion implementation defined ...


Trollsdale is famous for this sort of trick. He also revises
quotes without warning. Note his irrelevant referance to a stack,
in addition.


I hate to say this, but ERT's reference to a stack is actually
relevant in this context. He mentions it as one of the
implementation-specific ways arguments can be passed.

That doesn't excuse his deliberate snipping of context and replying as
if the previous poster hadn't already acknowleged that extern "C" is
implementation defined.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #95
On Thu, 1 Jan 2004 02:57:13 UTC, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Richard Heathfield wrote:
I write C programs for preference
but occasionally use C++ for RAD of GUI programs.
I don't see why I should forsake the use of my familiar C libraries
when writing C++ programs.


Who said that you should?
But I don't see why I should rewrite my C code
to be C++-compilable either.


Who said that you should?
So I simply call my C code from my C++ code. It works fine.


Please cite and quote the passage from the ANSI/ISO C++ standard
that *guarantees* that "it works fine".

C functions compiled by one compiler need not be callable
from programs compiled with any other compiler --
not even another C compiler.
The only way to guarantee that you can call C functions
from a C++ program is to compile them with the *same* C++ compiler.


Wrong. My C programs are using different functions in different
libraries compiled with compilers I've never seen. The truth is that
you have to define clearly the calling conventsions and interfaces you
should use. Anything else is definded by the liner - and not part of
the C language or the compiler itself.

I've used gcc to call functions in libraries written definitely with
IBM VAc++, and with Watcom. I use Watcom C to call fuctions in
libraries written with the C compiler of IBM VA C++ and GCC. I use the
C compiler in IBM VA C++ to call functions in libraries written with
other compilers.

I use even som functions definitely written in COBOL, fortran and
other languages. Some of them written in pure assembler too. But look,
the libraries are designed to have interfaces to most commonly used
languages - and for all C compilers - even such NOT existent at the
day the libraries were released.

A C compiler is designed to produce binaries, ready prepared to get
linked with a linker of your choice. An binary of a well designed
system is well designed to be understandable by any linker this system
environment knows or will known in forseable future.

You may link object module together to build an executeable program or
by inserting an interface module to build a library callable by any
language. Has nothing to do with the programming language you use to
write something in source.

The way from a source compilation unit to an executeable program or an
library is long. A C compiler is only starting point to get the source
translated into some kind of binary (or source) module that needs to
be handled by one or more other programs.

Me and thousends of other peoples have written programs in C who are
NOT understandable by any C compiler without passing another kind of
compiler prior, needing some different compilers of different sources
too to be linked separately, then commonly then again to get an
library that can linked at runtime to another program alreard exist to
extend its functionality on the fly.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #96
On Thu, 1 Jan 2004 02:39:30 UTC, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Richard Heathfield wrote:
I'm suggesting that, if you wish to use C code in a C++ program,
you can generally do it without recompiling the C code.


Really! Are you an expert in C/C++ interoperability now?

Tell us how you would do it
without compiling the C code with a C++ compiler.
Is your method guaranteed to work?

1. use a text edtor of your choice to write the sources that contains
the functions you likes to share with other languages
2. use a text editor of your choice to write one or more interface
file(s) (known as header files) to define the interfaces right use the
calling conventions your compiler supports to get the external entry
points described completely
3. use a C compiler of your choice to compile it error free with
highest warning level on,
tell the compiler to use the headers defined in step one to check
the definitions against the declarations
4. use a linker that is woth its name to build a library from the
object code your compiler generates
5. use the linker (or another program if they are separately on you
system) to build an interface module that generates an interface
module for the library that generates the needed object code to call
the library dynamically instead to bind it statically to a single
program. As this step is optionally, you will need it only to share
the same library with other programs at runtime.
6. use a text editor of your choice to write functions in another
programming language of your choice...... continue 2. - 5 to build
another libraries and object interfaces, replace C with C++, Fortran,
Pascal or any other langugae you knows of.

At least you gets many libraries written in many different languages
compiled with many different compilers together to many separately
compiled modules linked to single executeables whereas none of the
compilers knows of the others - but wors perfectly together.

But only step 3 has something to do with the topic of this newsgroup.
But this should show why Tisdale owns his nickname Twitsdale.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #97
On Thu, 1 Jan 2004 20:56:35 UTC, Sidney Cadot <si****@jigsaw.nl>
wrote:
Okay. Then we probably agree that Mr. Plauger at least has a valid
reason for wanting to compile C code using a C++ compiler.

There is none, not a single reason to recompile C code using something
that is NOT a C compiler. However use a C compiler to compile C code,
use a C++ compiler to compile C++ code use a <compiler of a language
of your choice> to compile <language of your choice> code. Use a
linker to build either a library of some to the compilation units
written in the same <language of your choice> and a linker again to
build the executeable of the other modules and again the linker to
link them together.

If you've done your homework right it works. Many times you can start
at compile stage on different mashines based on highly different
environments and anything works again.

Yes, you can't link directly object modules written in different
languages and compiled with different compilers - but linking
different libraries together is possible. Each partikular system will
give you the tools you need for.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #98
"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote in message
news:wmzsGguTDN6N-pn2-lwQoELwUNnY5@moon...
On Thu, 1 Jan 2004 20:56:35 UTC, Sidney Cadot <si****@jigsaw.nl>
wrote:
Okay. Then we probably agree that Mr. Plauger at least has a valid
reason for wanting to compile C code using a C++ compiler.

There is none, not a single reason to recompile C code using something
that is NOT a C compiler.


Oh, to have such certainty.

I still cherish a cartoon I clipped from Punch roughly half a
century ago. It shows two knights errant resting on horseback
beneath a tree. One says to the other, "Isn't life simple
when you know you're right all the time?"

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #99
In article <wmzsGguTDN6N-pn2-lwQoELwUNnY5@moon>, os****@pc-rosenau.de
says...
There is none, not a single reason to recompile C code using something
that is NOT a C compiler.


Or perhaps none that you can imagine, anyway. I am sure that Jack Klein
has a good reason or reasons, otherwise he would not be doing it. That
may or may not be true of others, especially ERT.

"When a distinguished but elderly scientist says that something is
possible, he is almost certainly right. When he says it is impossible,
he is very probably wrong."
-- Arthur C. Clarke
--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #100

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask...
3
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table...
10
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a...
10
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server...
53
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from...
3
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.