473,501 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why still use C?

no this is no trollposting and please don't get it wrong but iam very
curious why people still use C instead of other languages especially C++.

i heard people say C++ is slower than C but i can't believe that. in pieces
of the application where speed really matters you can still use "normal"
functions or even static methods which is basically the same.

in C there arent the simplest things present like constants, each struct and
enum have to be prefixed with "struct" and "enum". iam sure there is much
more.

i don't get it why people program in C and faking OOP features(function
pointers in structs..) instead of using C++. are they simply masochists or
is there a logical reason?

i feel C has to benefit against C++.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
--
comp.lang.c.moderated - moderation address: cl**@plethora.net
Nov 13 '05
687 22802
"cody" <do*********************@gmx.de> wrote:
<snip>

return 1 //* <-- the c version misses a semicolon here,
additionally //* will imho produce no valid comment in c.

-1 + 1; /* 0 in C99, 1 in C++ */
}


In C90: //* will be tokenized as
/ (division operator) followed by
/* (comment start)

In C99: //* will be tokenized as
// (single line comment start)

Thus, after stripping the comments and newlines

return 1 //*
-1 + 1; /* ... */

in C90 results in:

return 1 /

but in C99 results in:

return 1 -1 + 1;

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #251
"cody" <do*********************@gmx.de> wrote:
<snip>
What is a sig-monster?


I am a <insert your favourite attribute here> one. Groooarrrchrr.
--
Three is no spimle sbtsuuttie for cearful, cercrot,
wtlirtew-len Esglinh. Tehre is no slveir beullt.

- Rhacrid Hfiaehlted in comp.programming, 2003-09-25
Nov 13 '05 #252

"Brian Inglis" <Br**********@SystematicSw.ab.ca> wrote in message
news:41********************************@4ax.com...
An integer character constant is a sequence of one or more
multibyte characters enclosed in single-quotes, as in 'x'.

Was is the same in other versions of C besides C99?


As far back as K&R1 -- common C idiom was 'ab' (16 bit) or 'abcd'
(32 bit) to handle packed chars -- undefined behaviour as of C89
-- but still allowed and works?


Not undefined, implementation-defined in both C89 and C99.

Dennis
Nov 13 '05 #253
cody wrote:
> int i = sizeof (int);
> // int j = sizeof int; // invalid in both C and C++
> int k = sizeof i;
> int l = sizeof (i);
>
> The form of sizeof that gets a type as parameter has to use
> parantheses, while the sizeof that gets non-expressions as parameter do
> not need
them.

Wrong. In your example, i is an unary-expression, not a non-expression.


I don't know why i wrote non-expression. My example clearly showed how to
use sizeof:


It's improving, but still not quite there. You should really use size_t
rather than int here, and note that // comments are valid in C99 but /not/
in C90, and most of the world is still using C90, so they are best avoided,
at least for now.

The form of sizeof that gets a type (NON-EXPRESSION) as parameter has to
use parantheses,
while the sizeof that gets expressions (NON-TYPES) as parameter do not
need them.

Is it now correctly stated?


Why make up a description? Why not just say:

3.3.3.4 The sizeof operator

Constraints

The sizeof operator shall not be applied to an expression that has
function type or an incomplete type, to the parenthesized name of such
a type, or to an lvalue that designates a bit-field object.

Semantics

The sizeof operator yields the size (in bytes) of its operand,
which may be an expression or the parenthesized name of a type. The
size is determined from the type of the operand, which is not itself
evaluated. The result is an integer constant.

--
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 13 '05 #254
On Thu, 16 Oct 2003 23:57:20 +0200
"cody" <do*********************@gmx.de> wrote:
"Mark Gordon" <sp******@flash-gordon.me.uk> schrieb im Newsbeitrag
news:20031015232209.128f9a60.sp******@flash-gordon.me.uk...
On Wed, 15 Oct 2003 22:17:35 +0200
"cody" <do*********************@gmx.de> wrote:

Please don't trim the attributions since it prevents people from
seeing who said what.
> int test(int size)
> {
> int *new = malloc(size); /* two non-C++isms in this line
> */ return 1 //*
> -1 + 1; /* 0 in C99, 1 in C++ */
> }

is the missing semicolon at the end of a block allowed in C?
A semicolon is required to terminate every C statement, however in
C99 there is no missing semicolon in the above.

HINT: C99 added a form of // commenting.

int test(int size)
{
int *new = malloc(size); /* two non-C++isms in this line */

return 1 //* <-- the c version misses a semicolon

^^ This starts a comment, the * is just a commented
out character. here,
additionally //* will imho produce no valid comment in c.
In C99, once it has seen the // everything after on the line is
considered a comment.

Copied from section 6.4 of a copy of n897.pdf...

// comments were added for C9X ....

In certain unusual situations, code could have different semantics
for C90 and C9X. for example

a = b //*divisor:*/ c
+ d;

In C90 this was equivalent to

a = b c + d;

but in C9X it is equivalent to

a = b + d;

As you can see from the above in C99, //* is treated as a // style
comment the first character of which happens to be a * and the // style
comment ends at the end of the line. So for the example at the top in
C99, which is what it refers to, the first comment starts with a // and
ends at the end of the line, then the next line starts off not being a
comment until the /* ... */ style comment which is AFTER the semi-colon.

If neither myself nor whoever posted the example had referred to C99
then you would have been correct in thinking that there was a missing
semicolon.
-1 + 1; /* 0 in C99, 1 in C++ */ ^^^^^^^ not commented out because // comment ended at end
of last line. }


I'm sure that Dan or one of the others who know the C standards better
than me would have corrected me if I was wrong. They have certainly
corrected me in the past when I made mistakes and I definitely want them
to continue to point out anything I get wrong.
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.
Nov 13 '05 #255
cody wrote:
What is a sig-monster?


http://www.google.com/search?q=sig-monster

/Sven ;)

PS: No offence intended, but you should really start using stuff like
books and search engines. It makes your life far easier!

--
Remove "-usenet" from the email address to contact me.
Nov 13 '05 #256
Mark Gordon <sp******@flash-gordon.me.uk> wrote:
<snip>

In certain unusual situations, code could have different semantics
for C90 and C9X. for example

a = b //*divisor:*/ c
+ d;

In C90 this was equivalent to

a = b c + d; ITYM:
a = b / c + d;

I had a spare slash, so I thought I just place it in the gap :)

but in C9X it is equivalent to

a = b + d;

<snip>

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #257
"cody" <do*********************@gmx.de> wrote in message news:<bm************@ID-176797.news.uni-berlin.de>...
"Mark Gordon" <sp******@flash-gordon.me.uk> schrieb im Newsbeitrag
news:20031015232209.128f9a60.sp******@flash-gordon.me.uk...

....
HINT: C99 added a form of // commenting.

int test(int size)
{
int *new = malloc(size); /* two non-C++isms in this line */

return 1 //* <-- the c version misses a semicolon here,
additionally //* will imho produce no valid comment in c.

-1 + 1; /* 0 in C99, 1 in C++ */
}


You would be correct in C89, but not in C99 (see section 6.4.9). Did
you think that Mark Gordon was lying with his hint? Did you even
bother to check?

Both C99 and C++ recognise // comments, and the rules for handling
them are similar. In both languages, after comments have been removed,
your example code would look like:

int test(int size)
{
int *new = malloc(size);

return 1
additionally

-1 + 1;
}
In both languages, the word "additionally" is a syntax error, so I
suspect it was typo, or maybe an artifact of your lines getting
wrapped at the wrong location. In both languages, the absence of a
#include of a standard header file means that there's no prototype in
scope for your call to malloc(), which presents a problem in either
language (though the nature of the problem is slightly different in
each case).

Assuming that you add a line which says

#include <stdlib.h>

and move the "additionally" so that it's inside a comment, the code
still has a syntax error as far as C++ is concerned, because 'new' is
a keyword. However, both languages see a 'return' statement that is
correctly terminated by a ';', and the value returned would be 1, if
it weren't for the other problems.
Nov 13 '05 #258
On Fri, 17 Oct 2003 11:42:51 +0200
Irrwahn Grausewitz <ir*******@freenet.de> wrote:
Mark Gordon <sp******@flash-gordon.me.uk> wrote:
<snip>

In certain unusual situations, code could have different semantics
for C90 and C9X. for example

a = b //*divisor:*/ c
+ d;

In C90 this was equivalent to

a = b c + d;

ITYM:
a = b / c + d;

I had a spare slash, so I thought I just place it in the gap :)


Damn. I knew I should have bought more slashes when I went shopping last
weekend. :-)

Also proves my point that I would have been corrected if I had made a
mist ook.
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.
Nov 13 '05 #259
thp
In comp.std.c j <ja**********@bellsouth.net> wrote:
[...]
+ I don't know why people mold terms to fit things how they would like to see
+ them. C++ is not a superset, period. ``strict superset'' throw it out of the
+ window. When something is a ``superset'' of something else, that something else is
+ considered to be a ``subset''.
+ Now inorder for C to be a subset of C++, you would be able to compile _any_
+ C program with a C++ compiler. This can't be done, because C is not a subset
+ of C++, and that is because C++ is not a superset of C. It is a
+ ``derivative'' of C. Nothing more and nothing less.

C and C++ have a relatively large semantic intersection, i.e., set of
programs to which C and C++ attach identical behavior. It's my
impession that the intersecton includes the majority of actual C
programs.

Tom Payne

Nov 13 '05 #260
In article <bm**********@glue.ucr.edu>, th*@cs.ucr.edu wrote:
C and C++ have a relatively large semantic intersection, i.e., set of
programs to which C and C++ attach identical behavior. It's my
impession that the intersecton includes the majority of actual C
programs.


I think the majority of actual C programs will not compile as C++
programs at all; if the programmer never heard of C++ then it is just
too easy to have "new", "class" or "template" as an identifier.

However, the majority of actual C programs can be changed with little
effort into source code that has identical behavior as C and C++
programs. The most annoying difference is having to cast the result of
malloc in C++, which is considered bad practice in C and necessary in
C++.
Nov 13 '05 #261
th*@cs.ucr.edu wrote:
In comp.std.c j <ja**********@bellsouth.net> wrote:
[...]
+ Now inorder for C to be a subset of C++, you would be able to compile _any_
+ C program with a C++ compiler. This can't be done, because C is not a subset
+ of C++, and that is because C++ is not a superset of C. It is a
+ ``derivative'' of C. Nothing more and nothing less.
Correct.
C and C++ have a relatively large semantic intersection, i.e., set of
programs to which C and C++ attach identical behavior. It's my
impession that the intersecton includes the majority of actual C
programs.


It may be your impression, but if it would be like that in Reality[tm],
the majority of actual C programs would be bad C programs.
(Well, maybe they _are_, but that's not my point.)

If you don't believe this, feed some production level C code to a C++
compiler of your choice, but be prepared to face an army of nasal
demons. =%O

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #262
Christian Bau wrote:
[snip] However, the majority of actual C programs can be changed with little
effort into source code that has identical behavior as C and C++
programs. The most annoying difference is having to cast the result of
malloc in C++, which is considered bad practice in C and necessary in
C++.


Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

One advantage of casting malloc() results is that, like you say, one has
a fighting chance of getting a clean (error/warning-less) compile using
C++ in addition to getting a clean compile in C.

For me, compiling a piece of code with as many compilers as I can get my
hands on (with maximum warning levels) has proven to be a great way of
catching problems; different compilers give different warnings.

Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.

Best regards,

Sidney Cadot

Nov 13 '05 #263
Sidney Cadot <si****@jigsaw.nl> wrote:
Christian Bau wrote:
[snip]
However, the majority of actual C programs can be changed with little
effort into source code that has identical behavior as C and C++
programs. The most annoying difference is having to cast the result of
malloc in C++, which is considered bad practice in C and necessary in
C++.


Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.


1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.
Implicit conversions to/from pointer-to-void from/to any other
pointer-to-<type> are explicitly permitted in C.

2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.
One advantage of casting malloc() results is that, like you say, one has
a fighting chance of getting a clean (error/warning-less) compile using
C++ in addition to getting a clean compile in C.
If you feel the need to insert spurious casts to make your C code pass a
C++ compiler without complaints, well, just do so, but IMHO this doesn't
make it good coding style. It is probably feasible to make e.g. Pascal
programs pass C compilers, but you end up with something that is neither
well written Pascal nor well written C.
For me, compiling a piece of code with as many compilers as I can get my
hands on (with maximum warning levels) has proven to be a great way of
catching problems; different compilers give different warnings.
I second that, as long as all these are compilers for the language the
code is written in.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.


Can you please eloborate on this?
AFAIK now it is possible to write code that compiles fine, but has
different semantics when compiled as C or C++ respectively.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #264
Hi Irrwahn,
[[casting malloc() result to target type]]
Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.


There are circumstances where it is really needed of course, mostly in
low-level programming, and reading binary data formats. Casting is bad
if you just do it to shut down a compiler warning (I've assisted with
programming practicals at university, for novices this seems to be the
#1 reason to use casts), so you really have to understand what you're doing.
Implicit conversions to/from pointer-to-void from/to any other
pointer-to-<type> are explicitly permitted in C.
I think that is a mistake, and I am not going to drop casts that are not
needed just because the standard allows me to. I feel my code looks
prettier with malloc() casts.
2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.
If this is the case, I seriously doubt the quality of the compiler:

/* don't include stdlib.h */
int main(void)
{
char *x = (char *)malloc(100);
return 0;
}

The standard doesn't require the compiler to issue a warning of course
(never does), but I think, the year being AD2003 and all, that a
good-quality compiler should issue a warning whether the (char *) cast
is there or not.

/* don't include stdlib.h */
int main(void)
{
char *x = malloc(100);
return 0;
}

This version is legal C as well, so a compiler is free to not issue a
warning. So the only thing that is lost when including the (char *) cast
is that a compiler that would balk at program #2 might not balk at
program #1. I think that's a bad-quality compiler, and I think the
advantage of code that is both legal C and legal C++ outweighs the fact
that some bad compiler would fail to see the problem in program #1.
If you feel the need to insert spurious casts to make your C code pass a
C++ compiler without complaints, well, just do so, but IMHO this doesn't
make it good coding style.
I'm trying to argue it's not a black-and-white issue.
It is probably feasible to make e.g. Pascal
programs pass C compilers, but you end up with something that is neither
well written Pascal nor well written C.
Making a caricature of my position surely doesn't help much :-)
For me, compiling a piece of code with as many compilers as I can get my
hands on (with maximum warning levels) has proven to be a great way of
catching problems; different compilers give different warnings.


I second that, as long as all these are compilers for the language the
code is written in.


If, with minor hassle, it also passed C++, I think that's worth it,
given that C++ is (rightly, I think) stricter in some things than C.
Such as casting void pointers (one can disagree on that) and handling of
enums (see below).
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.

Can you please eloborate on this?
Example:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

enum EType {
a,b,c
};

void f(enum EType x)
{
switch(x)
{
case a: printf("a\n"); break;
case b: printf("b\n"); break;
case c: printf("c\n"); break;
default: printf("yikes!\n"); exit(1); break;
}
}

int main(void)
{
f(b);
f(1); /* uncasted call */
return 0;
}

This is a perfectly legal C program as far as I can tell, and it's
illegal in C++ due to the attempt to implicitly casting 1 to EType.

I think C++ is right to flag this as erroneous, and require a cast.
AFAIK now it is possible to write code that compiles fine, but has
different semantics when compiled as C or C++ respectively.


Sure it is possible. I am, however, advocating writing code that
complies with the intersection of C and C++, and works as intended. You
are coming perilously close to putting up a strawman here.

Best regards,

Sidney Cadot

Nov 13 '05 #265
Sidney Cadot wrote:
....
/* don't include stdlib.h */
int main(void)
{
char *x = malloc(100);
return 0;
}

This version is legal C as well, so a compiler is free to not issue a
warning.


It is not legal C. C99 requires a valid prototype and C89 does not
allow the assignment of int to char *. A diagnostic is *required*.

Jirka

Nov 13 '05 #266
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bm**********@news.tudelft.nl...
Hi Irrwahn,
[[casting malloc() result to target type]]

Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.

/snip/

Actually, casting the result of malloc() is *good*
programming practice, because it verifies that you
are assigning the result to the pointer-type that
you expect of the target variable.
fubar = (Gronk *) malloc(whatever_size_you_want);
This verifies that "fubar" is declared as a
pointer type to whatever Gronk is. If the
type of "fubar" is not (Gronk *), then the
compiler will complain about the pointer conversion.
The explicit cast clearly documents your intention
and allows the compiler to verify it.

OTOH, without the explicit cast, the compiler
will happily assign the (void*) result to fubar and
you won't know that you did something wrong. (Perhaps
you are assigning the result to the wrong variable?)

Finding burps like this at compile time is far more preferable
than tracking down runtime errors.

2 cents worth. Your mileage may vary.

Nov 13 '05 #267
Sidney Cadot wrote:
Christian Bau wrote:
[snip]

However, the majority of actual C programs can be changed with
little effort into source code that has identical behavior as C
and C++ programs. The most annoying difference is having to cast
the result of malloc in C++, which is considered bad practice in
C and necessary in C++.


Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

One advantage of casting malloc() results is that, like you say,
one has a fighting chance of getting a clean (error/warning-less)
compile using C++ in addition to getting a clean compile in C.


It can hide errors that the compiler could otherwise pick up. It
prevents controlling the type of that object in only one place,
and having all other code slaved to that.

Casts are fundamentally evil things, and very often serve only to
conceal errors.

I have yet to see a C++ compiler that does not have a C mode, and
there is no problem linking C++ code with C code when the headers
are properly designed.

--
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 13 '05 #268

On Sat, 18 Oct 2003, xarax wrote:

"Sidney Cadot" <si****@jigsaw.nl> wrote...
>> [[casting malloc() result to target type]]
>
>Why is it considered "bad practice"? I know it is frowned upon
>sometimes, but I fail to see the rationale for that.

1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.

Actually, casting the result of malloc() is *good*
programming practice, because it verifies that you
are assigning the result to the pointer-type that
you expect of the target variable.


That's just silly. You, as the programmer, already *know* the type
of the target object, correct? And besides, well-written (i.e.,
idiomatic for c.l.c) malloc calls don't require *any* type information,
correct *or* incorrect -- it lets the compiler handle all the type
information by itself. Which of the following is most likely to
do the right thing, given that the type of 'p' might be hard to
remember?

extern Gronk *p;

p = (Gronk *) malloc(sizeof (Gronk));
p = (Gronk *) malloc(sizeof *p);
p = malloc(sizeof (Gronk));
p = malloc(sizeof *p);
(Hint: the last one.)

fubar = (Gronk *) malloc(whatever_size_you_want);
Where 'whatever_size_you_want' is an integral multiple of
sizeof *fubar, sure. But in that case, why bother with the
cast?
This verifies that "fubar" is declared as a
pointer type to whatever Gronk is. If the
type of "fubar" is not (Gronk *), then the
compiler will complain about the pointer conversion.
The explicit cast clearly documents your intention
and allows the compiler to verify it.
True, but IMO not nearly as strong an argument as the "clarity,
brevity, and <stdlib.h> warning" arguments given by proponents
of the idiomatic (non-cast) style.

OTOH, without the explicit cast, the compiler
will happily assign the (void*) result to fubar and
you won't know that you did something wrong. (Perhaps
you are assigning the result to the wrong variable?)
Do you commonly write code in which two pointers to different
types are in scope at the same time? Unless you write compilers
for a living (which IMVLE often have pointers to symbol tables and
other things co-existing), I can't think of any context in which

Foo *my_foo;
Bar *my_bar;

my_bar = malloc(sizeof *my_foo);

could ever happen as a legitimate typo/error. And even if it
*did* happen, it's a fairly easy bug to find, especially now that
the code is made less cluttered by the removal of all those
spurious casts. Or did you have some other context in mind?

Finding burps like this at compile time is far more preferable
than tracking down runtime errors.

2 cents worth. Your mileage may vary.


MMDIV, as they say. You write a program with malloc casting that
you think will lose clarity or robustness by their removal, and I will
personally re-write the malloc-casting code to become clearer without
loss of robustness.

-Arthur
Nov 13 '05 #269
Sidney Cadot <si****@jigsaw.nl> wrote:
Hi Irrwahn,
[[casting malloc() result to target type]]

Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.
1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.


There are circumstances where it is really needed of course, mostly in
low-level programming, and reading binary data formats.


The special cases are the reason why I said "most probably" and not
"certainly". However, low-level code is unlikely to be pure portable
ISO-C anyway.
Casting is bad
if you just do it to shut down a compiler warning (I've assisted with
programming practicals at university, for novices this seems to be the
#1 reason to use casts), so you really have to understand what you're doing.
We both agree on this.
Implicit conversions to/from pointer-to-void from/to any other
pointer-to-<type> are explicitly permitted in C.


I think that is a mistake, and I am not going to drop casts that are not
needed just because the standard allows me to.


If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)
I feel my code looks
prettier with malloc() casts.
We couldn't disagree more on this aspect, but it's a style question and
therefore IMHO not /that/ important.
2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.


If this is the case, I seriously doubt the quality of the compiler:

/* don't include stdlib.h */
int main(void)
{
char *x = (char *)malloc(100);
return 0;
}


warning: implicit declaration of function `malloc'
result: undefined behaviour; malloc now returns int, but with the cast
you told the compiler: shut up, even if otherwise it would be
so kind to issue another warning (see below).
The standard doesn't require the compiler to issue a warning of course
(never does), but I think, the year being AD2003 and all, that a
good-quality compiler should issue a warning whether the (char *) cast
is there or not.
You rely upon the fact that an integer is wide enough to hold a pointer
value. This holds true for some implementations. It invokes undefined
behaviour on others and is therefore dangerous and completely
unportable.
/* don't include stdlib.h */
int main(void)
{
char *x = malloc(100);
return 0;
}
warning: implicit declaration of function `malloc'
warning: initialization makes pointer from integer without a cast
result: undefined behaviour
This version is legal C as well,
Not really. It invokes undefined behaviour, so a compiler is free to not issue a
warning. So the only thing that is lost when including the (char *) cast
is that a compiler that would balk at program #2 might not balk at
program #1.
Additionally you lost the chance of having well defined behaviour and
portability. Congratulations :^]
I think that's a bad-quality compiler, and I think the
advantage of code that is both legal C and legal C++ outweighs the fact
that some bad compiler would fail to see the problem in program #1.


So in your opinion a decent compiler should automagically know that the
return type of malloc is void *, without being told by a prototype.
I'm not aware of what implementations you have used so far, but I bet
all of them are bad-quality compilers according to your definition.
If you feel the need to insert spurious casts to make your C code pass a
C++ compiler without complaints, well, just do so, but IMHO this doesn't
make it good coding style.


I'm trying to argue it's not a black-and-white issue.


Well, style isn't, hiding errors IMO is.
It is probably feasible to make e.g. Pascal
programs pass C compilers, but you end up with something that is neither
well written Pascal nor well written C.


Making a caricature of my position surely doesn't help much :-)


Caricatures have the advantage of exposing certain aspects by hyperbole.
In one sense they are /defined/ that way. :o) Here's another one:
A perfectely valid Spanish sentence can also be a perfectly valid
Portugese sentence, but with a different meaning. The fact that both
are somewhat close related languages doens't make them compatible.
Moral: To order breakfeast using the wrong language can be dangerous.
For me, compiling a piece of code with as many compilers as I can get my
hands on (with maximum warning levels) has proven to be a great way of
catching problems; different compilers give different warnings.


I second that, as long as all these are compilers for the language the
code is written in.


If, with minor hassle, it also passed C++, I think that's worth it,
given that C++ is (rightly, I think) stricter in some things than C.
Such as casting void pointers (one can disagree on that) and handling of
enums (see below).


One has to weigh freedom against restriction. ;-)
If one prefers C++ over C for certain reasons, why not write C++ in the
first place, instead of breeding a chimera that's neither idiomatic C
nor idiomatic C++.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.
Can you please eloborate on this?


Example:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

enum EType {
a,b,c
};

void f(enum EType x)
{
switch(x)
{
case a: printf("a\n"); break;
case b: printf("b\n"); break;
case c: printf("c\n"); break;
default: printf("yikes!\n"); exit(1); break;
}
}

int main(void)
{
f(b);
f(1); /* uncasted call */
return 0;
}

This is a perfectly legal C program as far as I can tell, and it's
illegal in C++ due to the attempt to implicitly casting 1 to EType.

I think C++ is right to flag this as erroneous, and require a cast.


Hm, "right" depends of ones POV in this case. The C standard does not
require a diagnostic, so it is wrong? I don't think so. However, this
leaves us with the last issue:
AFAIK now it is possible to write code that compiles fine, but has
different semantics when compiled as C or C++ respectively.


Sure it is possible. I am, however, advocating writing code that
complies with the intersection of C and C++, and works as intended. You
are coming perilously close to putting up a strawman here.


Am I? Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference. Now who was how close to putting up a
strawman? ;-P

Regards, and have a nice weekend.
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #270
xarax wrote:
Actually, casting the result of malloc() is *good*
programming practice, because it verifies that you
are assigning the result to the pointer-type that
you expect of the target variable.
fubar = (Gronk *) malloc(whatever_size_you_want);
This verifies that "fubar" is declared as a
pointer type to whatever Gronk is.


It allows the compiler to suppress a possibly vital diagnostic. In any
event, if fubar isn't a Gronk *, then you're bound to find out fairly soon,
because lots of other stuff isn't going to compile.

What do you think of this code?

#include <stdio.h>

int main(void)
{
int i;
double d = (double)3.14;
i = (int)6;
(int)printf("%d %f\n", (int)i, (double)d);
return (int)0;
}

--
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 13 '05 #271
Jirka Klaue wrote:
Sidney Cadot wrote:
...
/* don't include stdlib.h */
int main(void)
{
char *x = malloc(100);
return 0;
}

This version is legal C as well, so a compiler is free to not issue a
warning.


It is not legal C. C99 requires a valid prototype and C89 does not
allow the assignment of int to char *. A diagnostic is *required*.


I stand corrected.

Could anybody point me to the last C89 draft standard that is publicly
available on the web? I have "n869.pdf" sitting on my HD for C99 which
is pretty useful and I would also like a similar document for C89.

If only to prevent silly mistakes like this.

Best regards,

Sidney Cadot

Nov 13 '05 #272
CBFalconer wrote:
[[ casting malloc() results ]]
Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

One advantage of casting malloc() results is that, like you say,
one has a fighting chance of getting a clean (error/warning-less)
compile using C++ in addition to getting a clean compile in C.

It can hide errors that the compiler could otherwise pick up. It
prevents controlling the type of that object in only one place,
and having all other code slaved to that.
Could you provide examples? I'm sure there are, but it's a lot easier to
discuss this over an example for me.
Casts are fundamentally evil things, and very often serve only to
conceal errors.
'fundamentally evil things' ... that's a bit harsh isn't it?

It would make an interesting exercise to write low-level C code (e.g.,
kernels or device drivers), without casts. Are you suggesting this is
practical?
I have yet to see a C++ compiler that does not have a C mode, and
there is no problem linking C++ code with C code when the headers
are properly designed.


Sure, but I want to write C code, but sometimes compile the program with
a C++ compiler to use the extra checks as required by a C++ compiler,
for flagging potential problems - is that so strange?

Best regards,

Sidney Cadot

Nov 13 '05 #273
Irrwahn Grausewitz wrote:
Implicit conversions to/from pointer-to-void from/to any other
pointer-to-<type> are explicitly permitted in C.
I think that is a mistake, and I am not going to drop casts that are not
needed just because the standard allows me to.


If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)


Perhaps I should do that! And hopefully I could convince them to retract
support for those butt-ugly // comments as well :-)
I feel my code looks prettier with malloc() casts. We couldn't disagree more on this aspect, but it's a style question and
therefore IMHO not /that/ important.
Yes.
2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.


If this is the case, I seriously doubt the quality of the compiler:

/* don't include stdlib.h */
int main(void)
{
char *x = (char *)malloc(100);
return 0;
}

warning: implicit declaration of function `malloc'
result: undefined behaviour; malloc now returns int, but with the cast
you told the compiler: shut up, even if otherwise it would be
so kind to issue another warning (see below).


Undefined behavior: for sure, but we're discussing compile-time behavior
now.

My point is that a decent modern compiler will warn on the implicit
declaration of malloc() anyway, with an appropriate warning level.
The standard doesn't require the compiler to issue a warning of course
(never does), but I think, the year being AD2003 and all, that a
good-quality compiler should issue a warning whether the (char *) cast
is there or not.


You rely upon the fact that an integer is wide enough to hold a pointer
value. This holds true for some implementations. It invokes undefined
behaviour on others and is therefore dangerous and completely
unportable.


Exactly. For clearness: I'm not advocating leaving out the "#include
<stdlib.h>" here; we're discussing the compile-time consequences of
forgetting this, when casting or not casting the result of a malloc().
/* don't include stdlib.h */
int main(void)
{
char *x = malloc(100);
return 0;
}

warning: implicit declaration of function `malloc'
warning: initialization makes pointer from integer without a cast
result: undefined behaviour

This version is legal C as well,

Not really.


So it was brought to my attention. I'm talking C89 here (in C99 you will
get an error anyway for lack of a prototype); what I meant to say is
that this is compilable under C89, possible without a warning. What I
didn't realize is that this will emit a required diagnostic
(pointer-to-int conversion).
It invokes undefined behaviour, so a compiler is free to not issue a
warning. So the only thing that is lost when including the (char *) cast
is that a compiler that would balk at program #2 might not balk at
program #1.


Additionally you lost the chance of having well defined behaviour and
portability. Congratulations :^]


Again, I'm not advocating leaving out #include <stdlib.h> ; we're just
comparing compile-time behavior for different malloc() handling.
I think that's a bad-quality compiler, and I think the
advantage of code that is both legal C and legal C++ outweighs the fact
that some bad compiler would fail to see the problem in program #1.


So in your opinion a decent compiler should automagically know that the
return type of malloc is void *, without being told by a prototype.


No, that's not what I said. My opinion is this: A decent C89 compiler
should be able to warn on non-prototyped functions being used, even
though C89 allows it.
I'm not aware of what implementations you have used so far, but I bet
all of them are bad-quality compilers according to your definition.
.... You misunderstood my definition. All compilers I've used are able to
warn on non-prototyped function usage.
[snipped a small bit...]
It is probably feasible to make e.g. Pascal
programs pass C compilers, but you end up with something that is neither
well written Pascal nor well written C.


Making a caricature of my position surely doesn't help much :-)


Caricatures have the advantage of exposing certain aspects by hyperbole.
In one sense they are /defined/ that way. :o)


Chapter and verse? :-)
Here's another one:
A perfectely valid Spanish sentence can also be a perfectly valid
Portugese sentence, but with a different meaning. The fact that both
are somewhat close related languages doens't make them compatible.
....Now suppose you have a machine that understands Spanish, and a
machine that understands Portugese. Both machines warn on incorrect
syntax and grammer in their respectively understood languages. Let's
also assume (to make the metaphor a bit more realistic) that Portugese
descends from Spanish, adding a few grammatic constructs, and that most
Spanish sentences (except from contrived examples) are also correct
Portugese (though not the other way round). Finally, let's assume
Portugese is a lot stricter concerning grammatical constructs; some
sentences that are legal Spanish but often lead to problems are
incorrect in Portugese.

Now we have a valid metaphor. I'm advocating that, if you try to write
problem-free Spanish, using both machines instead of just the Spanish
one can be of help.
If one prefers C++ over C for certain reasons, why not write C++ in the
first place, instead of breeding a chimera that's neither idiomatic C
nor idiomatic C++.
I would kindly refer you to my reply to Cody's questions of 5 october. I
prefer C for many reasons, but I also recognise that C++ aims to fix
some problems in C. I'm aiming for the 'best of both worlds' approach.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.

Can you please eloborate on this?


Example:

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

enum EType {
a,b,c
};

void f(enum EType x)
{
switch(x)
{
case a: printf("a\n"); break;
case b: printf("b\n"); break;
case c: printf("c\n"); break;
default: printf("yikes!\n"); exit(1); break;
}
}

int main(void)
{
f(b);
f(1); /* uncasted call */
return 0;
}

This is a perfectly legal C program as far as I can tell, and it's
illegal in C++ due to the attempt to implicitly casting 1 to EType.

I think C++ is right to flag this as erroneous, and require a cast.


Hm, "right" depends of ones POV in this case. The C standard does not
require a diagnostic, so it is wrong? I don't think so.


It's not wrong from the C standard's point-of-view, but then I feel the
C standard is wrong in this respect. The rationale for allowing implicit
int-to-enum conversion at the time was undoubtedly the desire to not
break existing code, but as far as I am concerned the time has come to
leave this behind for new code.
AFAIK now it is possible to write code that compiles fine, but has
different semantics when compiled as C or C++ respectively.


Sure it is possible. I am, however, advocating writing code that
complies with the intersection of C and C++, and works as intended. You
are coming perilously close to putting up a strawman here.

Am I? Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference.


What's so strange about the concept of the intersection of two related
languages for which standards exists? Now I'm quite willing to explain
what an intersection is and to provide pointers to the relevant
standards, but you will first have to explain to me what's so hard to
understand :-)
Now who was how close to putting up a strawman? ;-P
I think you were (I'm trying hard to avoid it), but I am happy to see
that we can resolve this without erecting, much less burning, any straw
men.
Regards, and have a nice weekend.


You too. I mean, what could be more fun than arguing coding style on
Saturday evening!

Sidney Cadot

Nov 13 '05 #274
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> wrote in message
news:Pi***********************************@unix42. andrew.cmu.edu...
Actually, casting the result of malloc() is *good*
programming practice, because it verifies that you
are assigning the result to the pointer-type that
you expect of the target variable.
That's just silly.


I don't mind your having your own style, but I do bridle at your
cavalier dismissal of a different one. You're just being parochial
and short sighted (if you enjoy name calling).
You, as the programmer, already *know* the type
of the target object, correct?
Not for long. Over time, there can be drift between the type of the
object you're trying to allocate and the type of the pointer object
where you want to store the address of the allocation. Once you get
in the habit of maintaining code that's decades old, you learn
where best to take out insurance. (Hint: insurance against a failure
to include <stdlib.h> is pretty short term, by comparison.)
And besides, well-written (i.e.,
idiomatic for c.l.c) malloc calls don't require *any* type information,
correct *or* incorrect -- it lets the compiler handle all the type
information by itself.
I agree you don't have to write the cast -- we did that intentionally,
for backward compatibility, when we added void * to Standard C. I
disagree that omitting the cast automatically makes for well written
code. That's just one idiom, not always the best one in all
circumstances.
Which of the following is most likely to
do the right thing, given that the type of 'p' might be hard to
remember?

extern Gronk *p;

p = (Gronk *) malloc(sizeof (Gronk));
p = (Gronk *) malloc(sizeof *p);
p = malloc(sizeof (Gronk));
p = malloc(sizeof *p);
(Hint: the last one.)
None of the above. I strongly prefer:

p = (Gronk *) malloc(N * sizeof (Gronk));

even when N is an explicit 1. (Though I do eliminate the sizeof
when the type is demonstrably a char type.)
fubar = (Gronk *) malloc(whatever_size_you_want);


Where 'whatever_size_you_want' is an integral multiple of
sizeof *fubar, sure.


Sure? How can you be sure when reviewing the code after some
other maintainer has fiddled with the declaration of Gronk?
How much searching will it take you to become sure again? And
what if you decide to just trust that the size is properly
constrained?
But in that case, why bother with the
cast?
To spend less time hunting bugs during maintenance?
This verifies that "fubar" is declared as a
pointer type to whatever Gronk is. If the
type of "fubar" is not (Gronk *), then the
compiler will complain about the pointer conversion.
The explicit cast clearly documents your intention
and allows the compiler to verify it.


True, but IMO not nearly as strong an argument as the "clarity,
brevity, and <stdlib.h> warning" arguments given by proponents
of the idiomatic (non-cast) style.


Fine, that's just YO. Doesn't make everybody else silly.
OTOH, without the explicit cast, the compiler
will happily assign the (void*) result to fubar and
you won't know that you did something wrong. (Perhaps
you are assigning the result to the wrong variable?)


Do you commonly write code in which two pointers to different
types are in scope at the same time?


Yep, all the time.
Unless you write compilers
for a living (which IMVLE often have pointers to symbol tables and
other things co-existing), I can't think of any context in which

Foo *my_foo;
Bar *my_bar;

my_bar = malloc(sizeof *my_foo);

could ever happen as a legitimate typo/error. And even if it
*did* happen, it's a fairly easy bug to find, especially now that
the code is made less cluttered by the removal of all those
spurious casts. Or did you have some other context in mind?


Glad you think so. I'm a firm believer in natural selection.
Finding burps like this at compile time is far more preferable
than tracking down runtime errors.

2 cents worth. Your mileage may vary.


MMDIV, as they say. You write a program with malloc casting that
you think will lose clarity or robustness by their removal, and I will
personally re-write the malloc-casting code to become clearer without
loss of robustness.


Feel free. FWIW, I used your style for over 20 years, including a decade
after I added void * to my compiler. Then one day, about ten years ago,
I sat down and added casts to every blessed malloc call in my living code
base. And I've never been sorry. A more curious person might wonder why.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 13 '05 #275
"Irrwahn Grausewitz" <ir*******@freenet.de> wrote in message
news:v1********************************@4ax.com...
1. You don't need the cast in C. If you have to cast (e.g. to shut up
a compiler warning) you most probably try to do something dangerous.
There are circumstances where it is really needed of course, mostly in
low-level programming, and reading binary data formats.


The special cases are the reason why I said "most probably" and not
"certainly". However, low-level code is unlikely to be pure portable
ISO-C anyway.


Gee, I just counted a couple of hundred casts in our C code, which runs
on a dozen or more platforms. I'd estimate that only a few per cent of
them could safely be removed, including the malloc ones. I agree that
casts can be dangerous, so I only write them when I think they serve
a good purpose. In the cases I just counted, almost all are needed to
*ensure* portability. Go figure.
Casting is bad
if you just do it to shut down a compiler warning (I've assisted with
programming practicals at university, for novices this seems to be the
#1 reason to use casts), so you really have to understand what you're doing.


We both agree on this.


I'd like to agree, but we also add casts to our code to silence compiler
warnings that are silly. (Why do some compilers complain about -x, where
x is unsigned, but say nothing about 0-x?) Our customers do *not* want
warning messages from our code, no matter how much we assure them that
we know what we're doing.
Implicit conversions to/from pointer-to-void from/to any other
pointer-to-<type> are explicitly permitted in C.


I think that is a mistake, and I am not going to drop casts that are not
needed just because the standard allows me to.


If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)


You may not like it, but it *was* intentional.
.....

One has to weigh freedom against restriction. ;-)
If one prefers C++ over C for certain reasons, why not write C++ in the
first place, instead of breeding a chimera that's neither idiomatic C
nor idiomatic C++.
Because it's idiomatic common subset, and superior for both purposes?
.....
AFAIK now it is possible to write code that compiles fine, but has
different semantics when compiled as C or C++ respectively.


Sure it is possible. I am, however, advocating writing code that
complies with the intersection of C and C++, and works as intended. You
are coming perilously close to putting up a strawman here.


Am I? Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference. Now who was how close to putting up a
strawman? ;-P


You are. You don't want to code in the common subset, don't. If you want
to learn how to write code that works the same way when compiled as C89,
C99, and C++, it ain't that hard. I feel no obligation to help educate
you, however.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 13 '05 #276
Sidney Cadot wrote:
CBFalconer wrote:
> [[ casting malloc() results ]]
Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

One advantage of casting malloc() results is that, like you say,
one has a fighting chance of getting a clean (error/warning-less)
compile using C++ in addition to getting a clean compile in C.

It can hide errors that the compiler could otherwise pick up. It
prevents controlling the type of that object in only one place,
and having all other code slaved to that.


Could you provide examples? I'm sure there are, but it's a lot easier to
discuss this over an example for me.


typedef struct foo {
....
} foo, *foop;
.....
foop barp;
.....
barp = malloc(count * sizeof *barp)

(which you can handle slighly differently if you don't approve of
typedefing structures.) At any rate, I can control what a foo (and
a foop) is in just one place, without needing to alter any other
code. I can also hide that definition in one module and export
only the foop type by slight changes in the declaration method.
Again, the rest of the code does not change.
Casts are fundamentally evil things, and very often serve only to
conceal errors.
'fundamentally evil things' ... that's a bit harsh isn't it?

It would make an interesting exercise to write low-level C code (e.g.,
kernels or device drivers), without casts. Are you suggesting this is
practical?


Certainly there are places where casts are needed. But they
should never be used without a clear understanding of their
purpose. "shutting up compiler complaints" is not a valid
reason. Code written without casts is much more likely to be
bugfree.
I have yet to see a C++ compiler that does not have a C mode, and
there is no problem linking C++ code with C code when the headers
are properly designed.


Sure, but I want to write C code, but sometimes compile the program with
a C++ compiler to use the extra checks as required by a C++ compiler,
for flagging potential problems - is that so strange?


That is what lint, pclint, splint (nee lclint) are for. splint is
also free. They are all much more picky than some nebulous C++
compiler, which is written for a different standard.

Please do not strip attributions for quoted material. I think you
stripped yourself in this case, but am not sure.

--
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 13 '05 #277
"xarax" <xa***@email.com> wrote:
"Sidney Cadot" <si****@jigsaw.nl> wrote in message
news:bm**********@news.tudelft.nl...
Hi Irrwahn,
>>> [[casting malloc() result to target type]]
>>
>>Why is it considered "bad practice"? I know it is frowned upon
>>sometimes, but I fail to see the rationale for that.
>
>
> 1. You don't need the cast in C. If you have to cast (e.g. to shut up
> a compiler warning) you most probably try to do something dangerous.
/snip/

Actually, casting the result of malloc() is *good*
programming practice, because it verifies that you
are assigning the result to the pointer-type that
you expect of the target variable.


And it's unnecessary, can hide errors and reduces the maintainability of
the code.
fubar = (Gronk *) malloc(whatever_size_you_want);
This verifies that "fubar" is declared as a
pointer type to whatever Gronk is.
But what tells you that Gronk * is the correct type for fubar to have?
And if you change the type of foobar you have to go through your code
and change the malloc calls. Why tell the Compiler something it already
knows? BTW: whatever_size_you_want seems to neither be related to
sizeof(Gronk) nor to sizeof *fubar.

IMO

fubar = malloc( desired_number * sizeof *fubar );

is much clearer.
If the
type of "fubar" is not (Gronk *), then the
compiler will complain about the pointer conversion.
The explicit cast clearly documents your intention
and allows the compiler to verify it.
That's a small benefit compared to the tradeoffs.
OTOH, without the explicit cast, the compiler
will happily assign the (void*) result to fubar and
you won't know that you did something wrong. (Perhaps
you are assigning the result to the wrong variable?)
Finding burps like this at compile time is far more preferable
than tracking down runtime errors.
Well, consequently you should cast _any_ assignment then. What a mess.
2 cents worth. Your mileage may vary.


My 2ct:
A compiler is not a suitable weapon against lapse of reason. ;-)

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #278
On Sat, 18 Oct 2003 09:27:07 +0000 (UTC), th*@cs.ucr.edu wrote:
C and C++ have a relatively large semantic intersection, i.e., set of
programs to which C and C++ attach identical behavior.
The one does not follow from the other.
It's my
impession that the intersecton includes the majority of actual C
programs.


#define true (1/(sizeof 'a' - 1))
--
#include <standard.disclaimer>
_
Kevin D Quitt USA 91387-4454 96.37% of all statistics are made up
Per the FCA, this address may not be added to any commercial mail list
Nov 13 '05 #279
CBFalconer wrote:
Sidney Cadot wrote:
CBFalconer wrote:
> [[ casting malloc() results ]]
Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

One advantage of casting malloc() results is that, like you say,
one has a fighting chance of getting a clean (error/warning-less)
compile using C++ in addition to getting a clean compile in C.

It can hide errors that the compiler could otherwise pick up. It
prevents controlling the type of that object in only one place,
and having all other code slaved to that.


Could you provide examples? I'm sure there are, but it's a lot easier to
discuss this over an example for me.

typedef struct foo {
....
} foo, *foop;
....
foop barp;
....
barp = malloc(count * sizeof *barp)

(which you can handle slighly differently if you don't approve of
typedefing structures.) At any rate, I can control what a foo (and
a foop) is in just one place, without needing to alter any other
code. I can also hide that definition in one module and export
only the foop type by slight changes in the declaration method.
Again, the rest of the code does not change.


How does all this keep you from writing this:

{
foop barp;
barp = (foop)malloc(count * sizeof *barp);
}

Only a name change of foop would be a slight hassle I think? I don't
quite see what changing the definition of the foo struct has to do with
casting the malloc result.
Casts are fundamentally evil things, and very often serve only to
conceal errors.


'fundamentally evil things' ... that's a bit harsh isn't it?

It would make an interesting exercise to write low-level C code (e.g.,
kernels or device drivers), without casts. Are you suggesting this is
practical?

Certainly there are places where casts are needed. But they
should never be used without a clear understanding of their
purpose. "shutting up compiler complaints" is not a valid
reason.


I agree insofar as that a compiler warning is an indication (symptom) of
an actual or potential problem, and that you should take care to solve
the problem instead of just curing the symptom.

As to whether "shutting up compiler complaints" is not a valid reason,
ever, I would hesitate to make this a dogma.
Code written without casts is much more likely to be bugfree.
Sure, but that's also in large part because the type of code that really
*needs* casts tends to solve complicated problems.
I have yet to see a C++ compiler that does not have a C mode, and
there is no problem linking C++ code with C code when the headers
are properly designed.


Sure, but I want to write C code, but sometimes compile the program with
a C++ compiler to use the extra checks as required by a C++ compiler,
for flagging potential problems - is that so strange?


That is what lint, pclint, splint (nee lclint) are for. splint is
also free. They are all much more picky than some nebulous C++
compiler, which is written for a different standard.


What's so nebulous about a C++ compiler? These pick up some of my
mistakes that a C compiler misses, it works for me. I'm sure the *lints
are nice tools as well. Have heard some good and bad things about them,
must try for myself one of these days.

As long as they have a flag for not complaining about malloc result
casts ... ;-)
Please do not strip attributions for quoted material. I think you
stripped yourself in this case, but am not sure.


Sorry about that.

Best regards,

Sidney Cadot

Nov 13 '05 #280
Kevin D. Quitt wrote:
On Sat, 18 Oct 2003 09:27:07 +0000 (UTC), th*@cs.ucr.edu wrote:
It's my
impession that the intersecton includes the majority of actual C
programs.


#define true (1/(sizeof 'a' - 1))


Um, this resolves to 1/0 in C++, and either 1/0 or 0 in C. None of these
values is typically associated with the concept of truth in either C or
C++. :-)

--
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 13 '05 #281
Kevin D. Quitt <KQ**********@IEEInc.MUNG.com> writes:
On Sat, 18 Oct 2003 09:27:07 +0000 (UTC), th*@cs.ucr.edu wrote:
C and C++ have a relatively large semantic intersection, i.e., set of
programs to which C and C++ attach identical behavior.


The one does not follow from the other.


What doesn't follow from what? I think Kevin is defining the term
"semantic intersection".
It's my
impession that the intersecton includes the majority of actual C
programs.


#define true (1/(sizeof 'a' - 1))


I'm reasonably sure that the majority of actual C programs do not
contain that macro definition.

I'm also reasonably sure that the majority of actual C programs do not
apply the sizeof operator to a character constant.

I haven't tried compiling a large body of C programs with a C++
compiler, but I'd guess that one of the most common sources of
incompatibility is calls to malloc() with no cast (legal and strongly
recommended in C, illegal in C++). Use of C++ keywords as identifiers
is probably less common, though it's certainly an issue.

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #282
On Sat, 18 Oct 2003 13:18:17 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw.nl> wrote:
Christian Bau wrote:
[snip]
However, the majority of actual C programs can be changed with little
effort into source code that has identical behavior as C and C++
programs. The most annoying difference is having to cast the result of
malloc in C++, which is considered bad practice in C and necessary in
C++.


Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.


The function of a cast is to silence a compiler warning. Thats not a
good idea, generally. Its easy to get carried away with them.
One advantage of casting malloc() results is that, like you say, one has
a fighting chance of getting a clean (error/warning-less) compile using
C++ in addition to getting a clean compile in C.
Clean in the sense of "doesn't warn about errors", yes. And this is
good because?
For me, compiling a piece of code with as many compilers as I can get my
hands on (with maximum warning levels) has proven to be a great way of
catching problems; different compilers give different warnings.
Indeed.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.


Thats a QOI issue. Get a better C compiler.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #283
On Sat, 18 Oct 2003 17:23:02 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw.nl> wrote:
and I am not going to drop casts that are not needed
just because the standard allows me to. I feel my code looks
prettier with malloc() casts.
what, you think this looks prettier
foo = (struct myweirdstruct*) malloc( sizeof (myweirdstruct));
than
foo = malloc (sizeof *foo);
???????
2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.


If this is the case, I seriously doubt the quality of the compiler:


Many compilers only *warn* about implicit function declarations on
their default warning level. My "many" I mean "pretty much all the
popular ones"
The standard doesn't require the compiler to issue a warning of course
(never does), but I think, the year being AD2003 and all, that a
good-quality compiler should issue a warning whether the (char *) cast
is there or not.
A warning is typically not a compilation halting operation. Thus
during an automated build, this error might go unnoticed.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.


<snip enum example claiming ti support this>
This is a perfectly legal C program as far as I can tell, and it's
illegal in C++ due to the attempt to implicitly casting 1 to EType.
but in C, this is not an error.
I think C++ is right to flag this as erroneous, and require a cast.


not in C, its not. Remember that enums are not a new type in C,
they're ints. So you are inserting another useless cast, obfuscating
your code slightly for no benefit.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #284
On Sat, 18 Oct 2003 20:13:58 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware.com> wrote:

Gee, I just counted a couple of hundred casts in our C code,


PJ we already know you're a heathen, so no need to chime in... :-)
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #285
Sidney Cadot <si****@jigsaw.nl> wrote:
Irrwahn Grausewitz wrote: <snip>
If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)


Perhaps I should do that! And hopefully I could convince them to retract
support for those butt-ugly // comments as well :-)


It's strange: I always wanted to have these single line comments in C,
now I can use them and already learnt to hate 'em :)

<snip>My point is that a decent modern compiler will warn on the implicit
declaration of malloc() anyway, with an appropriate warning level. <snip>Again, I'm not advocating leaving out #include <stdlib.h> ; we're just
comparing compile-time behavior for different malloc() handling. <snip>No, that's not what I said. My opinion is this: A decent C89 compiler
should be able to warn on non-prototyped functions being used, even
though C89 allows it. <snip>... You misunderstood my definition. All compilers I've used are able to
warn on non-prototyped function usage.
I was off-track then.

<snip>
Caricatures have the advantage of exposing certain aspects by hyperbole.
In one sense they are /defined/ that way. :o)


Chapter and verse? :-)


C99 6.2.8#2 :-))
Here's another one:
A perfectely valid Spanish sentence can also be a perfectly valid
Portugese sentence, but with a different meaning. The fact that both
are somewhat close related languages doens't make them compatible.


...Now suppose you have a machine that understands Spanish, and a
machine that understands Portugese. Both machines warn on incorrect
syntax and grammer in their respectively understood languages. Let's
also assume (to make the metaphor a bit more realistic) that Portugese
descends from Spanish, adding a few grammatic constructs, and that most
Spanish sentences (except from contrived examples) are also correct
Portugese (though not the other way round). Finally, let's assume
Portugese is a lot stricter concerning grammatical constructs; some
sentences that are legal Spanish but often lead to problems are
incorrect in Portugese.

Now we have a valid metaphor. I'm advocating that, if you try to write
problem-free Spanish, using both machines instead of just the Spanish
one can be of help.


But doing so you would have to avoid some common spanish idioms, which
will likely result in constructs that sound strange to native Spanish
speaking persons - the human readers of your code, to stress the
metaphor even more.

<snip>I would kindly refer you to my reply to Cody's questions of 5 october. I
prefer C for many reasons, but I also recognise that C++ aims to fix
some problems in C. I'm aiming for the 'best of both worlds' approach.
But why not use tools that are specially designed for testing C code?
What if the common subset of C and C++ becomes smaller after some more
revisions of the standards? The 'best of both worlds' may turn into the
'worst of both worlds' some day...

<example code snipped>
I think C++ is right to flag this as erroneous, and require a cast.


Hm, "right" depends of ones POV in this case. The C standard does not
require a diagnostic, so it is wrong? I don't think so.


It's not wrong from the C standard's point-of-view, but then I feel the
C standard is wrong in this respect. The rationale for allowing implicit
int-to-enum conversion at the time was undoubtedly the desire to not
break existing code, but as far as I am concerned the time has come to
leave this behind for new code.


I agree that the "oh no, don't break existing code" concept breeds the
danger of stagnation. And the "lack" of typesafety in C is, has been
and will probably always be a debatable point. I feel comfortable with
it as it is, otherwise I'd probably use some other language. Though
one has to watch ones step very carefully.

<snip>
Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference.


What's so strange about the concept of the intersection of two related
languages for which standards exists? Now I'm quite willing to explain
what an intersection is and to provide pointers to the relevant
standards, but you will first have to explain to me what's so hard to
understand :-)


Hm, seems to me you didn't get my point:
It's not the concept that's hard to understand, it's just that the
mentioned intersection isn't standardized. I don't like the idea
of having to change my coding style whenever each of the standards
changes. In fact, as long as I can't claim to have "incorporated" at
least 80% of _one_ standard, I won't bother to even try to define the
common subset of two (or three) standards. Maybe I'm just dumb. %O
Well, we could form a committee to exactely define the common subset
of both languages, but, er, well, what shall I say? :-)

<snip>I think you were (I'm trying hard to avoid it), but I am happy to see
that we can resolve this without erecting, much less burning, any straw
men.


Speaking of burning, I have to turn the heating on...
Regards, and have a nice weekend.


You too. I mean, what could be more fun than arguing coding style on
Saturday evening!


Definitely! ;-)

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #286
On Sat, 18 Oct 2003 23:04:51 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw.nl> wrote:
foop barp;
barp = (foop)malloc(count * sizeof *barp);


its not supposed to /prevent/ you from writing it, its supposed to
prevent you from /needing/ to write it.

By using CBF's method, you can change the type of barp, and ripple
that through all your code, by changing only one line of code, instead
of the 1000s of places you've malloced barps. Sure, you still have to
chagne places that you *use* a barp, but you've still reduced
maintenance costs sharply.

What do you thin that casting malloc does? How does it improve either
your code quality or readability? Its a serious question.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #287
On Sat, 18 Oct 2003 21:06:37 +0000 (UTC), in comp.lang.c , Richard
Heathfield <do******@address.co.uk.invalid> wrote:
Kevin D. Quitt wrote:
On Sat, 18 Oct 2003 09:27:07 +0000 (UTC), th*@cs.ucr.edu wrote:
It's my
impession that the intersecton includes the majority of actual C
programs.


#define true (1/(sizeof 'a' - 1))


Um, this resolves to 1/0 in C++, and either 1/0 or 0 in C. None of these
values is typically associated with the concept of truth in either C or
C++. :-)


Consider the value of "true" in juxtaposition with the previous
poster's statement.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #288
"Mark McIntyre" <ma**********@spamcop.net> wrote in message
news:nl********************************@4ax.com...
On Sat, 18 Oct 2003 20:13:58 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware.com> wrote:

Gee, I just counted a couple of hundred casts in our C code,


PJ we already know you're a heathen, so no need to chime in... :-)


Nice of you to notice. In fact, I've been officially recognized as
a heathen by the All Catholic Church. It's a point of pride with me.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 13 '05 #289
Mark McIntyre wrote:
[[casting malloc result]]
Why is it considered "bad practice"? I know it is frowned upon
sometimes, but I fail to see the rationale for that.

The function of a cast is to silence a compiler warning. Thats not a
good idea, generally. Its easy to get carried away with them.


That's a very negative way of putting it. As far as I am concerned, a
pointer cast is a way of expressing the fact that the compiler-inferred
type of the object pointed to by a pointer differs from the type that I,
the programmer, know to be the real type pointed at.

Sometimes the compiler cannot infer the type properly and needs a bit of
help. I would argue that the malloc() is just such a case.
One advantage of casting malloc() results is that, like you say, one has
a fighting chance of getting a clean (error/warning-less) compile using
C++ in addition to getting a clean compile in C.


Clean in the sense of "doesn't warn about errors", yes. And this is
good because?


I don't quite know what 'doesn't warn about errors' could mean, but
anyway. This is good because I can get my program compiled by the C++
compiler and get to an executable that I can run. This is an interesting
exercise, because any behaviorial mismatch between the program as
produced by the C compiler and by the C++ compiler could point to
something I have overlooked in the C code.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.


Thats a QOI issue. Get a better C compiler.


What C compiler would you recommend, if I want a warning on an integer
being passed for an enum parameter (as in my example)? Or would you say
that I am wrong in wanting this? Problems don't disappear by qualifying
them as QOI.

Best regards,

Sidney Cadot

Nov 13 '05 #290
Mark McIntyre wrote:
[...] I feel my code looks prettier with malloc() casts.
what, you think this looks prettier
foo = (struct myweirdstruct*) malloc( sizeof (myweirdstruct));
than
foo = malloc (sizeof *foo);
???????


Well yes, although I feel

foo = (struct myweirdstruct *)malloc(sizeof(struct myweirdstruct));

looks prettier still.
2. Casting malloc's return value may hide the (admittedly simple to fix)
error of not providing a proper prototype for malloc.


If this is the case, I seriously doubt the quality of the compiler:

Many compilers only *warn* about implicit function declarations on
their default warning level. My "many" I mean "pretty much all the
popular ones"


Pretty much all the popular ones also have an option to turn warnings
into errors, don't they?
The standard doesn't require the compiler to issue a warning of course
(never does), but I think, the year being AD2003 and all, that a
good-quality compiler should issue a warning whether the (char *) cast
is there or not.

A warning is typically not a compilation halting operation. Thus
during an automated build, this error might go unnoticed.


I either use -Werror with gcc or colormake, a few times a week.
Having one's C program compilable by a C++-compiler also helps, since
this can sometimes flag potential problems in the C code that are not
noticed by a C compiler.

<snip enum example claiming ti support this>


I think 'claiming to support' is a bit dismissive? I think my example is
excellent, actually! :-)
This is a perfectly legal C program as far as I can tell, and it's
illegal in C++ due to the attempt to implicitly casting 1 to EType. but in C, this is not an error.
That's my point. I think it should be an error. If I write a line like
f(1) where the parameter ought to be an enum I want to know. I have to
resort to C++ for that and the price-to-pay is casting malloc results.
I think C++ is right to flag this as erroneous, and require a cast.

not in C, its not. Remember that enums are not a new type in C,
they're ints. So you are inserting another useless cast, obfuscating
your code slightly for no benefit.


The benefit, I hesitate to repeat, is the ability to compile my C
program with a C++ compiler as well.

Best regards,

Sidney Cadot

Nov 13 '05 #291
"P.J. Plauger" <pj*@dinkumware.com> wrote:
"Irrwahn Grausewitz" <ir*******@freenet.de> wrote in message
news:v1********************************@4ax.com.. .
<snip>
The special cases are the reason why I said "most probably" and not
"certainly". However, low-level code is unlikely to be pure portable
ISO-C anyway.


Gee, I just counted a couple of hundred casts in our C code, which runs
on a dozen or more platforms. I'd estimate that only a few per cent of
them could safely be removed, including the malloc ones.


I admit that, coming from another programming domain, I made a frivolous
claim, but it's good to see that you[...] agree that
casts can be dangerous, so I only write them when I think they serve
a good purpose. In the cases I just counted, almost all are needed to
*ensure* portability. Go figure.
<snip>I'd like to agree, but we also add casts to our code to silence compiler
warnings that are silly. (Why do some compilers complain about -x, where
x is unsigned, but say nothing about 0-x?) Our customers do *not* want
warning messages from our code, no matter how much we assure them that
we know what we're doing.
Well, I consider silly compiler warnings to be an exceptional thing.

<snip>
>I think that is a mistake, and I am not going to drop casts that are not
>needed just because the standard allows me to.


If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)


You may not like it, but it *was* intentional.


Huh?!? Who do you mean by 'you', Sidney or me?

<snip>
If one prefers C++ over C for certain reasons, why not write C++ in the
first place, instead of breeding a chimera that's neither idiomatic C
nor idiomatic C++.


Because it's idiomatic common subset, and superior for both purposes?


The intersection of C and C++ excludes idioms of both languages. That's
not superior, it's a limitation.

<snip>
>... I am, however, advocating writing code that
>complies with the intersection of C and C++, and works as intended. You
>are coming perilously close to putting up a strawman here.


Am I? Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference. Now who was how close to putting up a
strawman? ;-P


You are. You don't want to code in the common subset, don't.


You, like Sidney, seem to have missed my point. Don't mind.
If you want
to learn how to write code that works the same way when compiled as C89,
C99, and C++, it ain't that hard.
Well, for non-experts like me it /is/ hard, to some extent.
I feel no obligation to help educate
you, however.


Thanks for offering no help, I'll stick to just writing C as good as I
can. ;-)

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #292
Irrwahn Grausewitz wrote:
[snippedysnip]
No, that's not what I said. My opinion is this: A decent C89 compiler
should be able to warn on non-prototyped functions being used, even
though C89 allows it.
<snip>
... You misunderstood my definition. All compilers I've used are able to
warn on non-prototyped function usage.


I was off-track then.


Ok, that's sorted out.
<snip>
Here's another one:
A perfectely valid Spanish sentence can also be a perfectly valid
Portugese sentence, but with a different meaning. The fact that both
are somewhat close related languages doens't make them compatible.


...Now suppose you have a machine that understands Spanish, and a
machine that understands Portugese. Both machines warn on incorrect
syntax and grammer in their respectively understood languages. Let's
also assume (to make the metaphor a bit more realistic) that Portugese
descends from Spanish, adding a few grammatic constructs, and that most
Spanish sentences (except from contrived examples) are also correct
Portugese (though not the other way round). Finally, let's assume
Portugese is a lot stricter concerning grammatical constructs; some
sentences that are legal Spanish but often lead to problems are
incorrect in Portugese.

Now we have a valid metaphor. I'm advocating that, if you try to write
problem-free Spanish, using both machines instead of just the Spanish
one can be of help.


But doing so you would have to avoid some common spanish idioms, which
will likely result in constructs that sound strange to native Spanish
speaking persons - the human readers of your code, to stress the
metaphor even more.


In practice, it's really almost exclusively the casting of malloc()
results you need to take care of, and avoiding a couple of C++-keywords,
to get C++-compliant code. The numbers of idioms to avoid is therefore
rather limited. And I have, in the past, reapt real benefits from
C++-compiling C-programs.

I would recommend to anybody to give this a shot... Cast the mallocs on
a smallish (1000--2000 line) C-program, and turn loose a C++-compiler on
it with maximum warning level. You may be surprised at what you get.
<snip>
I would kindly refer you to my reply to Cody's questions of 5 october. I
prefer C for many reasons, but I also recognise that C++ aims to fix
some problems in C. I'm aiming for the 'best of both worlds' approach.

But why not use tools that are specially designed for testing C code?
What if the common subset of C and C++ becomes smaller after some more
revisions of the standards? The 'best of both worlds' may turn into the
'worst of both worlds' some day...


One has to be practical in these matters. When divergence happens to the
point where taking care of C++ compliance of one's C code is no longer
possible, I will abandon this. Today it works for me.
<snip>
It's not wrong from the C standard's point-of-view, but then I feel the
C standard is wrong in this respect. The rationale for allowing implicit
int-to-enum conversion at the time was undoubtedly the desire to not
break existing code, but as far as I am concerned the time has come to
leave this behind for new code.
I agree that the "oh no, don't break existing code" concept breeds the
danger of stagnation. And the "lack" of typesafety in C is, has been
and will probably always be a debatable point. I feel comfortable with
it as it is, otherwise I'd probably use some other language. Though
one has to watch ones step very carefully.


Sure. I would love to have my steps monitored closely by the compiler
though.
<snip: language intersections>

Hm, seems to me you didn't get my point:
It's not the concept that's hard to understand, it's just that the
mentioned intersection isn't standardized. I don't like the idea
of having to change my coding style whenever each of the standards
changes.


Ok, that's a valid point. For now, it can be done; in 5 years, who
knows. Of course C and C++ are not (yet) developing independently;
there's cross-pollination and that's bound to keep 'em together for most
basic things in the years to come. My guess is, at the time when they
diverge, C will have a standard without implicit cast to/from void*.
Then again I could be wrong.
In fact, as long as I can't claim to have "incorporated" at

least 80% of _one_ standard, I won't bother to even try to define the
common subset of two (or three) standards. Maybe I'm just dumb. %O
Well, we could form a committee to exactely define the common subset
of both languages, but, er, well, what shall I say? :-)


Good plan. A good starting point would be the C++ standard without the
exceptions, templates, and STL parts.

(ducks)
Regards,

Sidney

Nov 13 '05 #293
Mark McIntyre wrote:
On Sat, 18 Oct 2003 23:04:51 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw.nl> wrote:

foop barp;
barp = (foop)malloc(count * sizeof *barp);

its not supposed to /prevent/ you from writing it, its supposed to
prevent you from /needing/ to write it.


Well, I need it to compile my program with a C++ compiler, so that
doesn't help.
By using CBF's method, you can change the type of barp, and ripple
that through all your code, by changing only one line of code, instead
of the 1000s of places you've malloced barps. Sure, you still have to
chagne places that you *use* a barp, but you've still reduced
maintenance costs sharply.
Let's not exagerrate the maintenance cost of such an operation. It's not
like I will have to look for a piece of hay in a massive stack of
needles, or anything... The compiler is my friend, also for this type of
renaming.
What do you thin that casting malloc does? How does it improve either
your code quality or readability? Its a serious question.


As I explained in a post of 20 minutes ago, I view a cast as a means of
setting a misguided compiler on the right course, with regard to the
type of an object a pointer points to.

Best regards,

Sidney Cadot


Nov 13 '05 #294
Sidney Cadot <si****@jigsaw.nl> wrote:
Mark McIntyre wrote:

[...]
what, you think this looks prettier
foo = (struct myweirdstruct*) malloc( sizeof (myweirdstruct));
than
foo = malloc (sizeof *foo);
???????


Well yes, although I feel

foo = (struct myweirdstruct *)malloc(sizeof(struct myweirdstruct));

looks prettier still.


Well, it's correct, as opposed to Marks first alternative, but anyway:

Beauty is in the eye of the beholder. :)

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #295
Sidney Cadot <si****@jigsaw.nl> wrote:
Irrwahn Grausewitz wrote: <much snippage>
Now we have a valid metaphor. I'm advocating that, if you try to write
problem-free Spanish, using both machines instead of just the Spanish
one can be of help.


But doing so you would have to avoid some common spanish idioms, which
will likely result in constructs that sound strange to native Spanish
speaking persons - the human readers of your code, to stress the
metaphor even more.


In practice, it's really almost exclusively the casting of malloc()
results you need to take care of, and avoiding a couple of C++-keywords,
to get C++-compliant code. The numbers of idioms to avoid is therefore
rather limited. And I have, in the past, reapt real benefits from
C++-compiling C-programs.


Well, I'm still not sure about that matter, but anyway: if it suits your
needs, do it, I most probably won't, but ...
I would recommend to anybody to give this a shot... Cast the mallocs on
a smallish (1000--2000 line) C-program, and turn loose a C++-compiler on
it with maximum warning level. You may be surprised at what you get.
.... maybe I'll give it a try occasionally.

<snip>
I agree that the "oh no, don't break existing code" concept breeds the
danger of stagnation. And the "lack" of typesafety in C is, has been
and will probably always be a debatable point. I feel comfortable with
it as it is, otherwise I'd probably use some other language. Though
one has to watch ones step very carefully.


Sure. I would love to have my steps monitored closely by the compiler
though.


Well, if it's for me, not too close, please ...

<snip: language intersections>
Ok, that's a valid point. For now, it can be done; in 5 years, who
knows. Of course C and C++ are not (yet) developing independently;
there's cross-pollination and that's bound to keep 'em together for most
basic things in the years to come. My guess is, at the time when they
diverge, C will have a standard without implicit cast to/from void*.
Then again I could be wrong.


Fair enough.
In fact, as long as I can't claim to have "incorporated" at
least 80% of _one_ standard, I won't bother to even try to define the
common subset of two (or three) standards. Maybe I'm just dumb. %O
Well, we could form a committee to exactely define the common subset
of both languages, but, er, well, what shall I say? :-)


Good plan. A good starting point would be the C++ standard without the
exceptions, templates, and STL parts.

(ducks)


Hehehe :D

Regards,
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #296
"Irrwahn Grausewitz" <ir*******@freenet.de> wrote in message
news:s9********************************@4ax.com...
I'd like to agree, but we also add casts to our code to silence compiler
warnings that are silly. (Why do some compilers complain about -x, where
x is unsigned, but say nothing about 0-x?) Our customers do *not* want
warning messages from our code, no matter how much we assure them that
we know what we're doing.
Well, I consider silly compiler warnings to be an exceptional thing.


If only that were true. When you ship a source package designed to compile
with many different compilers, you'd be surprised what the union of all
silly compiler warnings can add up to.
<snip>
>I think that is a mistake, and I am not going to drop casts that are not
>needed just because the standard allows me to.

If you think that C99 6.3.2.3 is a mistake, you should submit a DR or a
proposal to the standards comittee. ;-)
You may not like it, but it *was* intentional.


Huh?!? Who do you mean by 'you', Sidney or me?


Sorry, I was indeed pointing one back. Should have made that clearer.
If one prefers C++ over C for certain reasons, why not write C++ in the
first place, instead of breeding a chimera that's neither idiomatic C
nor idiomatic C++.


Because it's idiomatic common subset, and superior for both purposes?


The intersection of C and C++ excludes idioms of both languages. That's
not superior, it's a limitation.


Not necessarily. Programming languages must choose when to permit shorthand
and when to demand redundancy -- primarily in the interest of maximizing
readability and maintainability (IMO). I've found the common subset to be
a pretty good dialect in that regard.
<snip>
>... I am, however, advocating writing code that
>complies with the intersection of C and C++, and works as intended. You
>are coming perilously close to putting up a strawman here.

Am I? Then please tell me where the common subset of C and C++ is
defined, so I have something to make my code comply to, just in case I
want to code the same way you do; is it different for C89 compared to
C99? Please give a reference. Now who was how close to putting up a
strawman? ;-P


You are. You don't want to code in the common subset, don't.


You, like Sidney, seem to have missed my point. Don't mind.


I didn't miss your point, just chose not to address it. Once again, I
could have been clearer.
If you want
to learn how to write code that works the same way when compiled as C89,
C99, and C++, it ain't that hard.


Well, for non-experts like me it /is/ hard, to some extent.


In that case, dig up Tom Plum's book on C programming guidelines. IIRC,
it does indeed describe how to write "safer C" in the common subset --
if only as a stepping stone when migrating to C++.
I feel no obligation to help educate
you, however.


Thanks for offering no help, I'll stick to just writing C as good as I
can. ;-)


As I said before, that's fine with me.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 13 '05 #297
Mark McIntyre wrote:
The function of a cast is to silence a compiler warning.


Not so. The function of a cast is to convert "the value of the expression to
the named type." (Of course, it's the programmer's job to ensure that the
conversion is meaningful.)

--
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 13 '05 #298
Fergus Henderson <fj*@cs.mu.oz.au> wrote:
Jerry Feldman <ga********@blu.org> writes:
Keith Thompson <ks*@cts.com> wrote:
C++ has never been a strict superset of any version of C. C++ has
several keywords that are not reserved in C; that alone makes prevents
it from being a superset.


I agree that "C++ has never been a strict superset of any version of C",
but I disagree with your logic. A superset can define new keywords (and
comment operators).


A strict superset can't, if those keywords have names which are not
already reserved for use by the implementation, because adding new
keywords will invalidate existing C programs that happen to use those
keywords as identifiers.

Adding new comment operators can also change the meaning of existing code.
Consider the following program:

int main() {
printf(1//**/2
? "fail\n" : "pass\n");
return 0;
}

On a conforming C89 implementation, this will print "pass",
but on a C++ or C99 implementation, it will print "fail".

<snip>

Congratulations, you just "proved" that C99 isn't a superset[1] of C89.
;-P

[1] According to your definition of "superset".

Regards
--
Irrwahn
(ir*******@freenet.de)
--
comp.lang.c.moderated - moderation address: cl**@plethora.net
Nov 13 '05 #299
On 13 Oct 2003 18:49:35 GMT in comp.std.c, th*@cs.ucr.edu wrote:
In comp.std.c Douglas A. Gwyn <DA****@null.net> wrote:
+ th*@cs.ucr.edu wrote:
+> Compiling C programs with a C++ compiler has the benefit that C++
+> compilers are required to perform intermodule type checking. But I'm
+> told that this intermodule type checking is a curse when one tries to
+> use precompiled libraries that have been compiled on different C++
+> compilers, since that checking is usually based on name-mangling and
+> there is no name-mangling standard. (Perhaps others have more
+> experience with that issue.)
+
+ On essentially any platform there is a unique standard API
+ for C linkage. And it is easy to get that linkage from C++
+ by using "extern C". Therefore, libraries written in C are
+ readily used from both C and C++ applications. Libraries
+ that rely on C++-specific features (e.g. classes) are not
+ readily used from C applications.

Is it feasible to interpose a proxy library whose headers are
conforming C code that's compiled with a C++ compiler and that calls
functions from the C++ library?


What conclusions could be drawn from the "extern C" linkage?

Thanks. Take care, Brian Inglis Calgary, Alberta, Canada
--
Br**********@CSi.com (Brian dot Inglis at SystematicSw dot ab dot ca)
fake address use address above to reply
--
comp.lang.c.moderated - moderation address: cl**@plethora.net
Nov 13 '05 #300

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

Similar topics

3
11174
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
5772
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
22955
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
8430
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
8535
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
18213
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
6774
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
31339
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
23530
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
0
7054
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7238
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7285
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...
1
6942
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
4963
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4636
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3133
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3133
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
342
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.