473,385 Members | 2,028 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Segfault City

[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #1
162 6541
Richard Heathfield <in*****@invalid.invalid> writes:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


Interesting. I just tried it myself. Copy-and-pasting the program
was tedious, but once I did that there were no line-wrapping errors.
Perhaps it's a function of which browser you use.

Obviously the "//" comments won't work if you use strict C90 mode.

With "gcc -g -std=c99 -pedantic -Wall -W -O3 sieve.c -o sieve", I got:

sieve.c: In function `string2Number':
sieve.c:64: warning: comparison between signed and unsigned
sieve.c: In function `main':
sieve.c:202: warning: int format, time_t arg (arg 2)

The first is a comparison between an int and the result of strlen();
assuming no strings longer than 2**31-1 characters (on my 32-bit
system), this bug shouldn't cause any visible symptoms. Likewise, I
left the second bug in place, since both int and time_t happen to be
32-bit signed integers on the system I'm using. (If I were actually
going to use the program, I'd fix both bugs first.)

I got a quick seg fault when I ran it, because of the following really
dumb statement:

printf( strcat(strcat("Sieve of Eratosthenes primes from least prime >= %d ",
"to greatest prime <= %d\n"),
"Sieve contains %d entries\n"),
MAX(intStart, 3),
intFinish,
intSieveLimit );

Using "-fwritable-strings" avoided the seg fault, but messed up the
output (obviously it was still invoking undefined behavior).

I changed the above to use string literal catenation rather than
strcat():

printf( "Sieve of Eratosthenes primes from least prime >= %d "
"to greatest prime <= %d\n"
"Sieve contains %d entries\n",
MAX(intStart, 3),
intFinish,
intSieveLimit );

With that change, the program seems to work (its failure to indicate
that 2 is prime seems to be an intentional design flaw rather than a
coding error).

It's still a good example of ugly C (they're called argc and argv, not
intArgCount and strArgValues), and it could probably be written more
clearly in no more than half the space, but it's not nauseatingly bad.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 24 '06 #2
On 2006-06-24, Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

Just out of curiousity, did you stumble upon that while Googling your own
name? I'm not accusing you of arrogance, but it's interesting that he
mentions and insults you specifically in his preamble.
It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

Ooh. Segfault City. Where all bad programs go to die. :-)
(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 24 '06 #3
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors, such as the use of strcat in

printf( strcat(strcat("The %s program calculates primes ",
"in a user-specifiable range. "),
"Use the following syntax: %s"),
strArgValues[0],
SYNTAX_REMINDER );

It's evident from the introductory text that Edward isn't a C
practitioner (e.g., he mentions how he had to figure out the declaration
syntax for arrays) and is used to more object-oriented languages, and
the code, such as the above, makes it painfully evident that he doesn't
have anybody doing quality assurance of the code -- which, one is led
to believe, is used in some C.Sc. course.

Perhaps he'd be glad to receive some help about that?
CC: sp*********@yahoo.com, which I'm assuming is Edward G. Nilges.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jun 24 '06 #4
["Followup-To:" header set to comp.lang.c.]
On 2006-06-24, Alf P. Steinbach <al***@start.no> wrote:
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors


Judging by the same comments, Edward Nilges has already receieved some
corrections from Richard and was less than happy about it:

"Richard acidulously explained my assisting John Nash with C as an
instance of the ape with the typewriter, in fact."

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 24 '06 #5
Andrew Poelstra wrote:
On 2006-06-24, Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

Just out of curiousity, did you stumble upon that while Googling your own
name? I'm not accusing you of arrogance, but it's interesting that he
mentions and insults you specifically in his preamble.


Oooh, what fun! Richard is the target of a vendetta!
He'd better check his bed for horses' heads -- or perhaps
he needn't bother; the vendettor seems like someone who's
better acquainted with the opposite end of the animal.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jun 24 '06 #6
Andrew Poelstra <ap*******@localhost.localdomain> writes:
[...]
I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?


I probably would have if I'd read it before compiling it.

Here's the function you're probably talking about:
========================================
// Convert character to its numeric form
//
//
int char2Number( char chrInChar )
{
int intInCharValue = ( int )chrInChar;
int intZeroValue = ( int )'0';
if ( intInCharValue < intZeroValue
||
intInCharValue > ( int )'9' ) return -1;
return intInCharValue - intZeroValue;
}
========================================

If something is < '0' or > '9', it's not a digit, and the function
returns -1 as an error indication.

On first glance, I assumed that something that size would convert a
string to an integer ("123" --> 123). Then I realized it only
converts a single character.

It's really impressive how ugly this manages to be without actually
being incorrect.

I might have to read the rest of this thing, but I don't think I'll
burden the newsgroup with a critique that would probably be several
times as long as the actual code.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 24 '06 #7
On Sat, 24 Jun 2006 05:35:36 +0200, "Alf P. Steinbach"
<al***@start.no> wrote in comp.lang.c:
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors, such as the use of strcat in

printf( strcat(strcat("The %s program calculates primes ",
"in a user-specifiable range. "),
"Use the following syntax: %s"),
strArgValues[0],
SYNTAX_REMINDER );

It's evident from the introductory text that Edward isn't a C
practitioner (e.g., he mentions how he had to figure out the declaration
syntax for arrays) and is used to more object-oriented languages, and
the code, such as the above, makes it painfully evident that he doesn't
have anybody doing quality assurance of the code -- which, one is led
to believe, is used in some C.Sc. course.

Perhaps he'd be glad to receive some help about that?


Nilges is a bombastic, pedantic, and quite ignorant troll who used to
spew a lot of nonsense into comp.programming, and perhaps other groups
that I do not read regularly.

Perhaps he still does, I haven't seen any of his arrogant gibberish
since I added him to my kill file, long ago.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jun 24 '06 #8
"Alf P. Steinbach" <al***@start.no> writes:
* Richard Heathfield:
[X-posted, and followups set]
I found something interesting on the Web today, purely by chance.
It would be funny if it weren't so sad. Or sad if it weren't so
funny. I'm not sure which.
http://www.developerdotstar.com/community/node/291
This "teacher of C" demonstrates his prowess with a masterful
display of incompetence in a 200-line program that travels as
swiftly as possible to Segfault City.
(Actually, using my normal gcc switches, it doesn't even get past
TP3, but it will at least compile if you just use gcc -o foo foo.c,
after hacking it around a bit to do things like mending the
line-spanning single-line comments and string literals, which - in
fairness to the author - are probably an artifact of the
Webification of the code.)
I wonder how long I'll take to stop laughing.
I can understand you responding, Rirchard, since the web page contains
a comment about you, but I think it would have been more helpful to
Edward Nilges if you'd just sent him a private e-mail pointing out
some of the errors, such as the use of strcat in

Hardly I suggest you search for Nilges posts in the past and then you
know why Richard did what he did.
Perhaps he'd be glad to receive some help about that?

I doubt that really. He has shown a complete lack of insight in the
past. I doubt it has changed.

Regards
Friedrich
--
Please remove just-for-news- to reply via e-mail.
Jun 24 '06 #9
On 2006-06-24, Keith Thompson <ks***@mib.org> wrote:
Andrew Poelstra <ap*******@localhost.localdomain> writes:
[...]
I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?


I probably would have if I'd read it before compiling it.

Here's the function you're probably talking about:
========================================
// Convert character to its numeric form
//
//
int char2Number( char chrInChar )
{
int intInCharValue = ( int )chrInChar;
int intZeroValue = ( int )'0';
if ( intInCharValue < intZeroValue
||
intInCharValue > ( int )'9' ) return -1;
return intInCharValue - intZeroValue;
}
========================================

If something is < '0' or > '9', it's not a digit, and the function
returns -1 as an error indication.

On first glance, I assumed that something that size would convert a
string to an integer ("123" --> 123). Then I realized it only
converts a single character.

It's really impressive how ugly this manages to be without actually
being incorrect.

I might have to read the rest of this thing, but I don't think I'll
burden the newsgroup with a critique that would probably be several
times as long as the actual code.


I missed the "< '0'" because he disguised '0' behind a temp variable.
Indeed, 'tis ugly but not incorrect.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 24 '06 #10
On Sat, 24 Jun 2006 05:35:36 +0200, "Alf P. Steinbach"
<al***@start.no> wrote:
I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors, such as the use of strcat in


<giggle> It's Nilges? You probably don't know, Alf, but people have
been helpfully pointing out his errors for years. So far, it's had no
discernible effect.

--
Al Balmer
Sun City, AZ
Jun 24 '06 #11
Friedrich Dominicus <ju*****************@q-software-solutions.de> writes:
I can understand you responding, Rirchard, since the web page contains
a comment about you, but I think it would have been more helpful to
Edward Nilges if you'd just sent him a private e-mail pointing out
some of the errors, such as the use of strcat in

Hardly I suggest you search for Nilges posts in the past and then you
know why Richard did what he did.

Well here's one message in which Nilges shows his "knowledge" in C:
http://groups.google.de/group/comp.p...60a66e44c4c65d

Agreed it's a terrible link but look google for
#define MALLOCSTMT and you'll find it.

Around that same time he has posted some other severly broken code and
blaimed C for it. Ah threads with Nilges tend to get a bit large over
time.

Regards
Friedrich

--
Please remove just-for-news- to reply via e-mail.
Jun 24 '06 #12

Keith Thompson wrote:
Richard Heathfield <in*****@invalid.invalid> writes:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.
Interesting. I just tried it myself. Copy-and-pasting the program
was tedious, but once I did that there were no line-wrapping errors.
Perhaps it's a function of which browser you use.


If you try the printer friendly version of the page copy and pasting
is easy with no line-wrapping.
I got a quick seg fault when I ran it, because of the following really
dumb statement:

printf( strcat(strcat("Sieve of Eratosthenes primes from least prime >= %d ",
"to greatest prime <= %d\n"),
"Sieve contains %d entries\n"),
MAX(intStart, 3),
intFinish,
intSieveLimit );

Using "-fwritable-strings" avoided the seg fault, but messed up the
output (obviously it was still invoking undefined behavior).

I changed the above to use string literal catenation rather than
strcat():

printf( "Sieve of Eratosthenes primes from least prime >= %d "
"to greatest prime <= %d\n"
"Sieve contains %d entries\n",
MAX(intStart, 3),
intFinish,
intSieveLimit );
His use of strcat was very puzzling for me. Even if he doesn't know
that the compiler will concatenate strings why not use multiple
printf's ? The use of nested strcat's make it a lot less readable even
if it was working.
With that change, the program seems to work (its failure to indicate
that 2 is prime seems to be an intentional design flaw rather than a
coding error).


I haven't tried compiling it but I tried to read it and understand it.
After
a while I gave up. His general verbosity and use of Hungarian notation
in particular made it unreadable for me. Based on what I could
understand
I doubt that it actually implements Eratosthenes's sieve. Here's a
programme which does:

#include <stdio.h>
#define LIMIT 1000

int main() {
int sieve[LIMIT+1] , i , j ;

for (i=2 ; i<=LIMIT ; i++) sieve[i]=1 ;

for (i=2 ; i <= LIMIT/2 ; i++) {
for (j=2 ; i*j <= LIMIT ; j++) {
sieve[i*j] = 0 ;
}
}
for (i=2 ; i<=LIMIT ; i++) {
if (sieve[i]) printf("%d\n",i) ;
}
}

Spiros Bousbouras

Jun 24 '06 #13
Andrew Poelstra said:
On 2006-06-24, Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

Just out of curiousity, did you stumble upon that while Googling your own
name? I'm not accusing you of arrogance,


....just of self-indulgence. Yes, I was actually looking for a specific Terry
Pratchett quote. I knew it was on a page of quotations that /also/ quoted
something by me, but that's all I could remember, so I googled for my name
+ quote and Google showed me:

Wayne's World of C Code (The Sieve of Eratosthenes) | developer ...
[Richard Heathfield and his team have some good advice in his book, ... I
wish I could quote the whole column (or link to it--it's not available
online), ...
www.developerdotstar.com/community/node/291 - 59k - Cached - Similar pages

which looked promising, but alas, turned out to be junk after all.

<snip>
I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?


UCHAR_MAX + 1.0, I think, although if you have really amazingly colossal
chars you might manage to break it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #14
Keith Thompson wrote:
Andrew Poelstra <ap*******@localhost.localdomain> writes:
[...]
What, if anything, can it be guaranteed will be > '9' in standard C?

Here's the function you're probably talking about:
// Convert character to its numeric form
int char2Number( char chrInChar )
{
int intInCharValue = ( int )chrInChar;
int intZeroValue = ( int )'0';
if ( intInCharValue < intZeroValue
||
intInCharValue > ( int )'9' ) return -1;
return intInCharValue - intZeroValue;
}

If something is < '0' or > '9', it's not a digit, and the function
returns -1 as an error indication.


Char constant expressions '9' or '0' are type of int. Even if
they aren't, they will be promoted as type of int in the operations.
I'm not very clear on that, could you please give more hints?

And how do you feel about the following code snippet?

int ctoi(char c)
{
int i = -1;
if (c >= '0' && c <= '9')
{
i = c - '0';
}
return i;
}

lovecreatesbeauty

Jun 24 '06 #15
Andrew Poelstra wrote:
["Followup-To:" header set to comp.lang.c.]
On 2006-06-24, Alf P. Steinbach <al***@start.no> wrote:
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so
funny. I'm not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful
display of incompetence in a 200-line program that travels as
swiftly as possible to Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past
TP3, but it will at least compile if you just use gcc -o foo foo.c,
after hacking it around a bit to do things like mending the
line-spanning single-line comments and string literals, which - in
fairness to the author - are probably an artifact of the
Webification of the code.)

I wonder how long I'll take to stop laughing.


I can understand you responding, Rirchard, since the web page
contains a comment about you, but I think it would have been more
helpful to Edward Nilges if you'd just sent him a private e-mail
pointing out some of the errors


Judging by the same comments, Edward Nilges has already receieved some
corrections from Richard and was less than happy about it:

"Richard acidulously explained my assisting John Nash with C as an
instance of the ape with the typewriter, in fact."


I followed the link, but alas couldn't find any such comment from Richard.

--
==============
*Not a pedant*
==============
Jun 24 '06 #16
sp****@gmail.com said:
I doubt that it actually implements Eratosthenes's sieve. Here's a
programme which does:

#include <stdio.h>
#define LIMIT 1000

int main() {
int sieve[LIMIT+1] , i , j ;

for (i=2 ; i<=LIMIT ; i++) sieve[i]=1 ;

for (i=2 ; i <= LIMIT/2 ; i++) {
for (j=2 ; i*j <= LIMIT ; j++) {
sieve[i*j] = 0 ;
}
}
for (i=2 ; i<=LIMIT ; i++) {
if (sieve[i]) printf("%d\n",i) ;
}
}


A good start, and a fine jumping-off point from which to start looking for
optimisations. (Because the Sieve is O(n*n), optimisations are actually
worth doing.)

For example, cutting down the number of times the inner loop is executed is
useful.

Here's an interesting fact about prime numbers for you:

Given any number-that-divides-by-6, n, we have the following cases:

n - multiple of 2, 3
n + 1 - might be prime
n + 2 - multiple of 2
n + 3 - multiple of 3
n + 4 - multiple of 2
n + 5 - might be prime

So if n >= 6 and n % 6 == 0, we can throw away two thirds of the cases
without even trial-dividing them.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #17

Richard Heathfield wrote:
sp****@gmail.com said:
I doubt that it actually implements Eratosthenes's sieve. Here's a
programme which does:

#include <stdio.h>
#define LIMIT 1000

int main() {
int sieve[LIMIT+1] , i , j ;

for (i=2 ; i<=LIMIT ; i++) sieve[i]=1 ;

for (i=2 ; i <= LIMIT/2 ; i++) {
for (j=2 ; i*j <= LIMIT ; j++) {
sieve[i*j] = 0 ;
}
}
for (i=2 ; i<=LIMIT ; i++) {
if (sieve[i]) printf("%d\n",i) ;
}
}


A good start, and a fine jumping-off point from which to start looking for
optimisations. (Because the Sieve is O(n*n), optimisations are actually
worth doing.)

For example, cutting down the number of times the inner loop is executed is
useful.

Here's an interesting fact about prime numbers for you:

Given any number-that-divides-by-6, n, we have the following cases:

n - multiple of 2, 3
n + 1 - might be prime
n + 2 - multiple of 2
n + 3 - multiple of 3
n + 4 - multiple of 2
n + 5 - might be prime

So if n >= 6 and n % 6 == 0, we can throw away two thirds of the cases
without even trial-dividing them.


I see no direct way of using this but there is an obvious improvement
to be made.

#include <stdio.h>
#define LIMIT 1000

int main() {
int sieve[LIMIT+1] , i , j ;

for (i=2 ; i<=LIMIT ; i++) sieve[i]=1 ;

for (i=2 ; i <= LIMIT/2 ; i++) {
if (!sieve[i]) continue ;
for (j=2 ; i*j <= LIMIT ; j++) {
sieve[i*j] = 0 ;
}
}
for (i=2 ; i<=LIMIT ; i++) {
if (sieve[i]) printf("%d\n",i) ;
}
}

I wonder what's the complexity of this. O(n*logn) perhaps ?

Spiros Bousbouras

Jun 24 '06 #18
Alf P. Steinbach wrote:
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.
I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors, such as the use of strcat in

printf( strcat(strcat("The %s program calculates primes ",
"in a user-specifiable range. "),
"Use the following syntax: %s"),
strArgValues[0],
SYNTAX_REMINDER );

It's evident from the introductory text that Edward isn't a C
practitioner (e.g., he mentions how he had to figure out the declaration
syntax for arrays) and is used to more object-oriented languages, and


Actually, I started in machine language. And as it happened I had to
refigure the syntax since I had (briefly) started re-using C.
the code, such as the above, makes it painfully evident that he doesn't
have anybody doing quality assurance of the code -- which, one is led
to believe, is used in some C.Sc. course.
You are clearly a loser. You don't even know that a professional would
not feel right about using a management puff phrase like "quality
assurance" (which usually and in practice means the eradication of
anything like quality) but would instead post reasons why he felt the
code to be incorrect. It may be (code is like that) but after several
months' hiatus I see nothing wrong.

The code ran on the Navia compiler. Do illumine us.

Perhaps he'd be glad to receive some help about that?
Not from people whose main interest is establishing their shaky
self-confidence exclusively on sand (silicon) by tearing down others.

Who are afraid to make CONSTRUCTIVE suggestions for modification, since
they might recursively be flamed because when you make a CONSTRUCTIVE
suggestion it contains other than negative assertions, and each one is
recursively subject to lampoon by people as "wrong" who cannot even say
why in clear English, but must instead refer to the idiosyncrasies of
their favorite compiler.

This discussion is useless. I have written enough code to be far more
interested in my competence in more important areas of life (such as
common decency) than "competing" with thugs...who were not invited to
post at a moderated site, and will be excluded should they choose to do
so in this matter by the moderator.



CC: sp*********@yahoo.com, which I'm assuming is Edward G. Nilges.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


Jun 24 '06 #19

sp*********@yahoo.com wrote:
You are clearly a loser.


Goodie , a flame war !
<Sits back in seat with pop-corn in hand>

Spiros Bousbouras

Jun 24 '06 #20

sp****@gmail.com wrote:
sp*********@yahoo.com wrote:
You are clearly a loser.
Goodie , a flame war !
<Sits back in seat with pop-corn in hand>


:-) Glad to oblige. Right you swine...
Spiros Bousbouras


Jun 24 '06 #21
pemo wrote:

Andrew Poelstra wrote:

Judging by the same comments,
Edward Nilges has already receieved some
corrections from Richard and was less than happy about it:

"Richard acidulously explained my assisting John Nash with C as an
instance of the ape with the typewriter, in fact."


I followed the link,
but alas couldn't find any such comment from Richard.


You can google on the phrase "theft of intellectual property"
in comp.programming, to see how he responded
to seeing a posted corrected version of some of his code.

--
pete
Jun 24 '06 #22

Richard Heathfield wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.
Where? On your system? And are you sure you know how to set all those
fancy switches, dear Richard?

Seriously, a professional would say in as neutral a way as possible, so
as not to give unnecessary offense, what he found and why he thinks it
is wrong. But we knew you are a hack and not a professional.

Furthermore, to make a positive assertion as opposed to a snide and
actionably libelous negative assertion exposes the former, recursively,
to attack and this would threaten your dominance of this intellectual
slum.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
I didn't use the Gnu compiler with what I shudder to think might be
what you believe a normal combination of its switches. Given that C is
such a primitive language, the actual result of any one compile with
any one setting of the large numbers of switches provided by gcc is of
course going to be precise but not in general predictable for any one
program.

I used the free Navia compiler, instead, with default settings.

It's already obvious to me that you are at best a paraprofessional, who
seriously recommends C for new development. I'd hazard that your C
environment is that of a Mad Scientist:

I was working in the lab late one night
When my eyes beheld an eerie sight

I am certain that when you pull C code (that you can't write yourself)
from the Web, you have to fiddle with your elaborate installation to
make it work. Here, you libelously make vague assertions that somehow
this reflects on the code in question because you were wounded in your
sense of dominance of comp.programming in 2000.
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)
Did it run? Note, again, that you make negative assertions rather than
positive contributions because your goal here is the same as your goal
with Herb Schildt: libeling people who threaten your shaky
self-confidence and self-esteem.
I wonder how long I'll take to stop laughing.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Jun 24 '06 #23

Keith Thompson wrote:

....a fairly good analysis of the program and its bug, which was to use
strcat without necessarily having the memory for the output. This was
my bad, and thanks to Keith Thompson for pointing it out. I will
correct the program at the moderated site.

Yes, I'd used strcat in that way because I was returning to C after
several years. I'd posted the rather trivial code because I'd
developed it for a class precisely to get word of any bugs. However,
Richard Heathfield has chosen to embarass himself by starting an
unneeded flame war, which he's gonna lose.
Richard Heathfield <in*****@invalid.invalid> writes:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
I taught C at Princeton and assisted Nash with it when I was using it
every day in the early 1990s. But when OO languages became available, I
abandoned it because it was impossible to manage large data structures
properly in this language (Richard H thinks it's possible, which only
indicates his limitations).

At the time this code was written I was out of money and starting a new
career in Hong Kong, and was thinking of returning to C in order to
develop as cheaply as possible. However, Microsoft has issued free
releases of C# and other languages, and I should have used C++ in this
example and others.

In fact, given that I'm so fucking smart :-), my really stupid error in
using strcat into an unknown region that would cause a segment fault in
many cases (but didn't on my system) illustrates that C is inadequate
for new development.
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.
Interesting. I just tried it myself. Copy-and-pasting the program
was tedious, but once I did that there were no line-wrapping errors.
Perhaps it's a function of which browser you use.


Har har har. Yeah, well, let's not confuse Richard, Keith.

Obviously the "//" comments won't work if you use strict C90 mode.
Oh fuck me. Actually, comment prefixes are damned if you do and damned
if you don't. If I'd used balance slash asterisk, someone would have
complained here, because scoring geek points is so terribly important.

Yes, // are "new". They are also a sanity saver and I like them a lot.

With "gcc -g -std=c99 -pedantic -Wall -W -O3 sieve.c -o sieve", I got:

sieve.c: In function `string2Number':
sieve.c:64: warning: comparison between signed and unsigned
sieve.c: In function `main':
sieve.c:202: warning: int format, time_t arg (arg 2)

The first is a comparison between an int and the result of strlen();
assuming no strings longer than 2**31-1 characters (on my 32-bit
system), this bug shouldn't cause any visible symptoms. Likewise, I
left the second bug in place, since both int and time_t happen to be
32-bit signed integers on the system I'm using. (If I were actually
going to use the program, I'd fix both bugs first.)
Is this a result of -pedantic?

In C sharp these issues don't arise, because it doesn't make the error
of making length a separate type from a number.

I should probably have set a -pedantic switch in Navia to catch this
because I agree that warnings are bad.
I got a quick seg fault when I ran it, because of the following really
dumb statement:

printf( strcat(strcat("Sieve of Eratosthenes primes from least prime >= %d ",
"to greatest prime <= %d\n"),
"Sieve contains %d entries\n"),
MAX(intStart, 3),
intFinish,
intSieveLimit );

Using "-fwritable-strings" avoided the seg fault, but messed up the
output (obviously it was still invoking undefined behavior).
Yes, this is the real brain fart on my part. I'd gotten used to
concatenating constants in strings because modern compilers, as I point
out in my book, concatenate them at compile time (well, my book
compiler does, and it was recently written therefore modern). I
"unnecessarily" break up strings for readability (lines that don't
scroll off the right side of the screen) but my formatting ASSUMES
courier new or another monospaced font. I could use XML but it is not
WYSIWYG.

I changed the above to use string literal catenation rather than
strcat():

printf( "Sieve of Eratosthenes primes from least prime >= %d "
"to greatest prime <= %d\n"
"Sieve contains %d entries\n",
MAX(intStart, 3),
intFinish,
intSieveLimit );
I've never seen what looks like Rexx above. It appears to use the rexx
rule that two adjacent strings with no intervening op are joined by
implicit concatenation. Is this part of the C standard, and if so, what
standard?

[Note: since I'm a professional and Keith is being one too, I don't
say, you fucking idiot that statement is wrong. Let this be an example
unto ye because we are making actual progress here. We learn how
foolish it is to strcat when you don't know you have the memory, etc.]

With that change, the program seems to work (its failure to indicate
that 2 is prime seems to be an intentional design flaw rather than a
coding error).
An "intentional design flaw"? Whuzzat? I would never do such a thing.

I think we can trust nearly anybody to know that 2 is prime (whether 1
is seems to be questionable).

It's still a good example of ugly C (they're called argc and argv, not
intArgCount and strArgValues), and it could probably be written more
Nope, they are called what I called them. The abandonment of Hungarian
notation was a mistake.
clearly in no more than half the space, but it's not nauseatingly bad.
I am glad you did not throw up. I agree that it's bad and based on this
discussion I will fix the strcat problem.

The program was written in an hour for a class, and today I like to
publish everything I can publish to get as much feedback as possible. I
thank you for an excellent example of CONSTRUCTIVE criticism where you
take the chance of being recursively (or iteratively wrong).

Now, on to the flamewar with the trolls...
--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


Jun 24 '06 #24

Andrew Poelstra wrote:
On 2006-06-24, Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

Just out of curiousity, did you stumble upon that while Googling your own
name? I'm not accusing you of arrogance, but it's interesting that he
mentions and insults you specifically in his preamble.
It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.


Ooh. Segfault City. Where all bad programs go to die. :-)
(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


I stopped reading after the first function. I wasn't sure why he kept


Which disqualifies you from a technical discussion. Why are you
posting?
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.
It was a straightforward test for numerics. Again, are you qualified to
be in this discussion?

You stopped trying to understand things twice, so your opinion is
worth...what?

What, if anything, can it be guaranteed will be > '9' in standard C?
This isn't grammatical therefore I do not fully understand it. If you
are saying there is no character greater than 9, well I wish you all
the best in your future career. You'll need it.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.


Jun 24 '06 #25
sp*********@yahoo.com said:
Seriously, a professional would say in as neutral a way as possible, so
as not to give unnecessary offense, what he found and why he thinks it
is wrong.
What I found: http://www.developerdotstar.com/community/node/291

Why I think it's wrong:

1) It doesn't survive past TP3.
2) If I hack it so it does, it segfaults.
3) A single glance at the code is sufficient to reveal the cause
of the segfault.
But we knew you are a hack and not a professional.
But the code *doesn't work*. You have an odd definition of "professional".
Furthermore, to make a positive assertion [...]
....I am positive, for example, that you should not be teaching people how to
write C programs.

(Actually, using my normal gcc switches, it doesn't even get past TP3,
but


I didn't use the Gnu compiler with what I shudder to think might be
what you believe a normal combination of its switches.


Might have been an idea to try it, even without the switches. Still.
Given that C is
such a primitive language, the actual result of any one compile with
any one setting of the large numbers of switches provided by gcc is of
course going to be precise but not in general predictable for any one
program.
Well, /my/ programs are predictable. Clearly, yours are a little more
exciting than that. You never know /when/ they'll segfault.

I used the free Navia compiler, instead, with default settings.
<grin> Figures.

It's already obvious to me that you are at best a paraprofessional, who
seriously recommends C for new development. I'd hazard that your C
environment is that of a Mad Scientist:
My C environment is basically bash/vim/gcc/gdb/gprof. Fairly normal setup,
really.
I am certain that when you pull C code (that you can't write yourself)
from the Web, you have to fiddle with your elaborate installation to
make it work.
Why? If it's properly written in standard C, it'll work out of the box. And
if it isn't, why would I want to make it work? I'll just find something
that does (if, as you say, I can't write it myself).
Did it run?


If "Segmentation fault (core dumped)" was the output you were expecting,
then yes, it ran perfectly. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #26
Alf P. Steinbach wrote:
* Richard Heathfield:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.
I can understand you responding, Rirchard, since the web page contains a
comment about you, but I think it would have been more helpful to Edward
Nilges if you'd just sent him a private e-mail pointing out some of the
errors, such as the use of strcat in

printf( strcat(strcat("The %s program calculates primes ",
"in a user-specifiable range. "),
"Use the following syntax: %s"),
strArgValues[0],
SYNTAX_REMINDER );

It's evident from the introductory text that Edward isn't a C
practitioner (e.g., he mentions how he had to figure out the declaration
syntax for arrays) and is used to more object-oriented languages, and
the code, such as the above, makes it painfully evident that he doesn't
have anybody doing quality assurance of the code -- which, one is led
to believe, is used in some C.Sc. course.

Perhaps he'd be glad to receive some help about that?
CC: sp*********@yahoo.com, which I'm assuming is Edward G. Nilges.


This is spinoza1111 who is Edward G. Nilges, author of Build Your Own
..Net Language and Compiler [and please, don't use C, thank you very
much.]

I was a daily C practitioner in the early 1990s and daily had to call
to mind things such as "don't strcat into an area where you don't have
the memory". For this reason, I assisted "a beautiful mind" with C.

I abandoned C shortly thereafter because each time I realized a new
deficiency, a new source of undefined behavior, I would write a
preprocessor macro or similar tool to encapsulate the cure.
Unfortunately, the Greek word for cure is also the word for poison, and
I realized after talking to my object-oriented Yi number one son that I
needed to learn OO, because the tool claptrap was more work than
solving problems.

The code isn't used in a class. It was used merely to give an example
to a math teacher where I work of the algorithm.

Yes, I would have appreciated a private email. But Richard seems to
like flame wars, and I am happy to oblige.

So now we have more data smog, a new thread called "segfault city",
because I WILL respond to libel.

It would be funny if it weren't so sad.

Richard has it seems a track record of leading vicious attacks by
Armies of Darkness on people who publish books other than himself. In
the 1990s, he conducted such an attack on Herb Schildt because Herb had
concealed some facts about C from the tyro in the interests of
TEACHING, something which bores Richard because it requires the TEACHER
to be something other than a narcissist.

Richard's delusion is that there is some sort of Platonic "C" and he is
its prophet. What there is is only praxis, and the language was so
primitively defined that it's not possible to write a correct compiler,
in the sense that the C community would ever agree that this is the
correct C compiler.

A language that permits aliasing in the way C permits aliasing is
*unteidscheidbar* undecidable all the way down. Whereas C# was
carefully designed to adhere not only to a syntax but to a runtime
standard defined by ECMA, as was Java, and it makes sense in these
languages to talk about the One Way.

I agree that Java libraries change the meaning of Java programs and
interact as do proteins with DNA. But the undecidability is
quantitatively less.

Richard joins the sad legion of people who mistake the contents of
their minds, their precise understanding of the Concept at a particular
time, with Absolute Truth.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


Jun 24 '06 #27
sp*********@yahoo.com said:
Yes, I'd used strcat in that way because I was returning to C after
several years.
That's what you said last time you posted some duff C, too, which was in
2002 or possibly 2003.
I'd posted the rather trivial code because I'd
developed it for a class precisely to get word of any bugs.
Those who claim to *teach* C should have a thorough understanding of the
language. That printf indicates that you don't even have a /basic/
understanding.

<snip>
> This "teacher of C" demonstrates his prowess with a masterful display
> of


I taught C at Princeton and assisted Nash with it when I was using it
every day in the early 1990s.


Lots of employers will now be checking their C programmers' CVs to find out
whether they learned C at Princeton in the early 1990s.

By Nilges' own admission, the "assistance" he gave to John Nash consisted
IIRC of suggesting the use of a compiler that used 32-bit ints rather than
16-bit ints. He has been dining out on this "assistance" ever since.
But when OO languages became available, I
abandoned it because it was impossible to manage large data structures
properly in this language (Richard H thinks it's possible, which only
indicates his limitations).
<grin> Yeah, that's right - if people can manage large data structures
properly in C, then *obviously* they have limitations compared to those who
can't.

<snip>
In fact, given that I'm so [elided] smart :-), my really stupid error in
using strcat into an unknown region that would cause a segment fault in
many cases (but didn't on my system) illustrates that C is inadequate
for new development.


A good engineer doesn't blame the wheel when the real problem is the nut
behind it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #28

Keith Thompson wrote:
Andrew Poelstra <ap*******@localhost.localdomain> writes:
[...]
I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?
I probably would have if I'd read it before compiling it.

Here's the function you're probably talking about:
========================================
// Convert character to its numeric form
//
//
int char2Number( char chrInChar )
{
int intInCharValue = ( int )chrInChar;
int intZeroValue = ( int )'0';
if ( intInCharValue < intZeroValue
||
intInCharValue > ( int )'9' ) return -1;
return intInCharValue - intZeroValue;
}
========================================

If something is < '0' or > '9', it's not a digit, and the function
returns -1 as an error indication.

On first glance, I assumed that something that size would convert a
string to an integer ("123" --> 123). Then I realized it only
converts a single character.

It's really impressive how ugly this manages to be without actually
being incorrect.


Mind of the beholder. You like short code. I find it easier to explain
longer identifiers.

But here, as opposed to your eariler post, you fall into the habit of
casting aspersions.

Why is code with short identifiers "ugly"?

The English language is also a world language. Nearly all world
programmers know English. Fewer use a standard set of abbreviations or
single characters in a fixed way: not even i always means "index".

I conclude that the best way to globally communicate the intent of an
identifier is to, within reason, spell it out. intCharValue is the
value of the character. It's an int. The Hungarian complements the
English nicely...in my opinion, and, I'm probably right.

Not sure what is "ugly" about trying to communicate, not just to
Amerikkkan geeks but to world programmers.

Not sure what is "beautiful" about adopting the all-too-ingrained
habits of the lead lawn troll in some little "community" and repeating
his mistakes. I'm well aware that "standard" C style uses argc and argv
but the letter c simply is too vague to mean "count".

Indeed, if you use what you call a "beautiful" style, you end up with a
Mandarin style. Ancient Chinese texts are incomprehensible, in my
experience working in China, to well-educated Chinese who had a
technical and scientific education in the mainland, yet my English
students in Hong Kong educated with traditional characters and ancient
texts persist in finding simplified Chinese characters and a modern
style "ugly" even though it does in fact a better job in communicating.

Richard the Heathfield may be a sort of C mandarin, insisting in the
teeth of the facts that his style is "clear and beautiful".

Of course, I might be the mandarin. I'm not communicating with you with
full success. But, you understood the intent of the code.
I might have to read the rest of this thing, but I don't think I'll
burden the newsgroup with a critique that would probably be several
times as long as the actual code.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


Jun 24 '06 #29
sp*********@yahoo.com said:

Andrew Poelstra wrote:

I stopped reading after the first function. I wasn't sure why he kept
Which disqualifies you from a technical discussion.


No, it doesn't, because he can always go back and read it if he wishes. And
he is certainly qualified to discuss the part he has read.
Why are you posting?
Why are you?
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me.
Realizing that I wouldn't be able to trace that logic, I stopped.


It was a straightforward test for numerics.


No, it wasn't even remotely straightforward. It was unnecessarily verbose.

This would be a straightforward test for numerics:

int to_digit(int ch)
{
return isdigit((unsigned char)ch) ? ch - '0' : -1;
}

If you think that's too obfuscated, here's another, which I don't like very
much as it trades structural elegance for simplicity, but it /is/ simple:

int to_digit(int ch)
{
if(isdigit((unsigned char)ch))
{
return ch - '0';
}
return -1;
}

Again, are you qualified to be in this discussion?
As much as you are, and probably more.

You stopped trying to understand things twice, so your opinion is
worth...what?


Plenty. What he's saying is that your code is unnecessarily obscure and
difficult to read. That's the mark of a bad programmer, unless your intent
is to win the IOCCC.
What, if anything, can it be guaranteed will be > '9' in standard C?


This isn't grammatical therefore I do not fully understand it. If you
are saying there is no character greater than 9, well I wish you all
the best in your future career. You'll need it.


C offers no guarantee that there is any character with a code point higher
than '9'. In EBCDIC, the code point of '9' is 249, so there are just six
characters (none with well-defined interpretations) with higher code
points. So Andrew's point is perfectly valid. It was also sufficiently
grammatical than I could understand it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #30

sp****@gmail.com wrote:
Keith Thompson wrote:
Richard Heathfield <in*****@invalid.invalid> writes:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.
Interesting. I just tried it myself. Copy-and-pasting the program
was tedious, but once I did that there were no line-wrapping errors.
Perhaps it's a function of which browser you use.


If you try the printer friendly version of the page copy and pasting
is easy with no line-wrapping.
I got a quick seg fault when I ran it, because of the following really
dumb statement:

printf( strcat(strcat("Sieve of Eratosthenes primes from least prime >= %d ",
"to greatest prime <= %d\n"),
"Sieve contains %d entries\n"),
MAX(intStart, 3),
intFinish,
intSieveLimit );

Using "-fwritable-strings" avoided the seg fault, but messed up the
output (obviously it was still invoking undefined behavior).

I changed the above to use string literal catenation rather than
strcat():

printf( "Sieve of Eratosthenes primes from least prime >= %d "
"to greatest prime <= %d\n"
"Sieve contains %d entries\n",
MAX(intStart, 3),
intFinish,
intSieveLimit );


His use of strcat was very puzzling for me. Even if he doesn't know
that the compiler will concatenate strings why not use multiple
printf's ? The use of nested strcat's make it a lot less readable even
if it was working.


I know that a good compiler will not only concatenate literal strings
it will evaluate constant expressions at compile time,because my quick
basic compiler does this. What puzzles me is the implication elsewhere
that if two strings appear, either adjacently or on separate lines,
they will be magically concatenated as in rexx. You may be right.

The nested strcats suck because I believe I missed the fact that no
space was allocated for them.
With that change, the program seems to work (its failure to indicate
that 2 is prime seems to be an intentional design flaw rather than a
coding error).
I haven't tried compiling it but I tried to read it and understand it.
After
a while I gave up. His general verbosity and use of Hungarian notation
in particular made it unreadable for me. Based on what I could
understand
I doubt that it actually implements Eratosthenes's sieve. Here's a


It did on my system. I posted it for critique and have here received
some useful information from Keith Thompson. But Heathfield posted it
here in bad faith and maliciously in order to get a sequence of posts
that make negative claims without constructively pointing out errors in
such a way that the criticiser could be criticised.

Par for the course on comp.whatever in usenet. programme which does:

#include <stdio.h>
#define LIMIT 1000

int main() {
int sieve[LIMIT+1] , i , j ;

for (i=2 ; i<=LIMIT ; i++) sieve[i]=1 ;

for (i=2 ; i <= LIMIT/2 ; i++) {
for (j=2 ; i*j <= LIMIT ; j++) {
sieve[i*j] = 0 ;
}
}
for (i=2 ; i<=LIMIT ; i++) {
if (sieve[i]) printf("%d\n",i) ;
}
}

Spiros Bousbouras


Jun 24 '06 #31
sp*********@yahoo.com wrote:
Keith Thompson wrote:

It's still a good example of ugly C (they're called argc and argv,
not intArgCount and strArgValues), and it could probably be written
more


Nope, they are called what I called them. The abandonment of Hungarian
notation was a mistake.
I think Keith's comment on argc/argv is right, i.e., using argc/argv follows
the rule of keeping 'the least possible surprise value' to a minimium. It's
what's 'expected' - I feel that there's no good reason for changing the
parameter names, and doing so will only cause confusion somewhere down the
line.

On Hungarian Notation, a few years ago [oh, now that I come to think about
it, that's quite a few years ago] I would have agreed with you - I used HN
all of the time, and liked it once I got used to it [I *had* to adopt their
use where I worked].

However, IMHO, modern development environments makes their use redundant -
now, if you want to know the type-of-something, its storage-class, or where
it's declared/defined - you simply use some shortcut/gesture built into the
development environment and you'll get all the information you need. And
that's great - this kind of feature, when used with meaningful names makes
code more readable [more easily parsable, and kinder on the eye]. In fact,
in dropping them, it might also make one think just a little harder about
the 'usage' part of any name used?
--
==============
*Not a pedant*
==============
Jun 24 '06 #32

Richard Heathfield wrote:
Andrew Poelstra said:
On 2006-06-24, Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

Just out of curiousity, did you stumble upon that while Googling your own
name? I'm not accusing you of arrogance,


...just of self-indulgence. Yes, I was actually looking for a specific Terry
Pratchett quote. I knew it was on a page of quotations that /also/ quoted
something by me, but that's all I could remember, so I googled for my name
+ quote and Google showed me:

Wayne's World of C Code (The Sieve of Eratosthenes) | developer ...
[Richard Heathfield and his team have some good advice in his book, ... I
wish I could quote the whole column (or link to it--it's not available
online), ...
www.developerdotstar.com/community/node/291 - 59k - Cached - Similar pages

which looked promising, but alas, turned out to be junk after all.

<snip>

I stopped reading after the first function. I wasn't sure why he kept
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me. Realizing
that I wouldn't be able to trace that logic, I stopped.

What, if anything, can it be guaranteed will be > '9' in standard C?


UCHAR_MAX + 1.0, I think, although if you have really amazingly colossal
chars you might manage to break it.


Do enlighten us, Richard. I was testing the character 9 which isn't the
highest value character, in ascii or unicode or even ebcdic. Has your
favorite standard defined '9' as the perfect character? Alert the
media!
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Jun 24 '06 #33
sp*********@yahoo.com said:
Richard Heathfield wrote:
Andrew Poelstra said:
<snip>
>
> What, if anything, can it be guaranteed will be > '9' in standard C?
UCHAR_MAX + 1.0, I think, although if you have really amazingly colossal
chars you might manage to break it.


Do enlighten us, Richard. I was testing the character 9 which isn't the
highest value character,


The C Standard does not guarantee that. It's a minor point.
in ascii or unicode or even ebcdic.
Curiously, it /is/ the highest EBCDIC character with a well-defined meaning,
although it is certainly true that there are half a dozen slots above it.
Has your
favorite standard defined '9' as the perfect character?


No, but neither has it guaranteed that '9' is not the highest character.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #34
On Sat, 24 Jun 2006 02:22:02 +0000, in comp.lang.c , Richard
Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291


I'm assuming you remember Edward G Nilges from his brief habitation
under a bridge here in CLC?
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jun 24 '06 #35

Richard Heathfield wrote:
sp*********@yahoo.com said:

Andrew Poelstra wrote:

I stopped reading after the first function. I wasn't sure why he kept
Which disqualifies you from a technical discussion.


No, it doesn't, because he can always go back and read it if he wishes. And
he is certainly qualified to discuss the part he has read.
Why are you posting?


Why are you?


Because you're engaged in a campaign of personal destruction as you
were with Schildt.
casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me.
Realizing that I wouldn't be able to trace that logic, I stopped.
It was a straightforward test for numerics.


No, it wasn't even remotely straightforward. It was unnecessarily verbose.

This would be a straightforward test for numerics:

int to_digit(int ch)
{
return isdigit((unsigned char)ch) ? ch - '0' : -1;
}

If you think that's too obfuscated, here's another, which I don't like very
much as it trades structural elegance for simplicity, but it /is/ simple:

int to_digit(int ch)
{
if(isdigit((unsigned char)ch))
{
return ch - '0';
}
return -1;
}

Again, are you qualified to be in this discussion?


As much as you are, and probably more.


Expressed fairly enough.

You stopped trying to understand things twice, so your opinion is
worth...what?
Plenty. What he's saying is that your code is unnecessarily obscure and
difficult to read. That's the mark of a bad programmer, unless your intent
is to win the IOCCC.


No, the mark of a bad programmer is inability to think outside the
particular set of chosen inputs and your insistence that C is still
usable for new development.
What, if anything, can it be guaranteed will be > '9' in standard C?
This isn't grammatical therefore I do not fully understand it. If you
are saying there is no character greater than 9, well I wish you all
the best in your future career. You'll need it.


C offers no guarantee that there is any character with a code point higher
than '9'. In EBCDIC, the code point of '9' is 249, so there are just six
characters (none with well-defined interpretations) with higher code
points. So Andrew's point is perfectly valid. It was also sufficiently
grammatical than I could understand it.


OK, this is complete nonsense. Are you pulling my leg?

You read in the standard that "C offers no guarantee with a code
point..."

But it MEANS that there CAN be. Can you read?

And to use EBCDIC, a completely obsolete encoding, obsoleted by ASCII
and then international 16 bit encoding...the mind boggles!

In ASCII, for which nearly all C code is written, the letters follow
the numbers! If the user enters A your "correct code" breaks?

[The "standard" may require the C runtime to treat the digits as
following the characters. The fact is that real compilers don't, and
use the encoded value. What this illustrates is the UNUSABILITY of the
standard, and consequently that it is extremely unwise, to the level of
professional malpractice, to recommend C for new development, as you
appear to.]

Are you for real? And you are sitting on your fat ass telling me I
don't know how to program?

But then you say that there are "just 6 characters" as if the small
number of characters makes it probable that your code won't break!

"My program is standard C, therefore the user has no right to send
characters with t a value higher than 9" is the zenith of arrogance.

And you use this as a reason for presenting code which BREAKS if there
IS a code point after all (c - 0 with no test for greater than 9)????

This is worse than I thought.

You seem to be using C on an IBM mainframe with the SAS compiler, and
pompously talking about C based on a misreading of the standard!

And if your compiler runs on an ASCII system, it has to jiggle
characters at runtime to make sure 9 is the "last" character. And C is
an "efficient" language?

Without being even aware that given aliasing, C can't be standardized
in a modern sense?

And icing on the cake..."it was also sufficiently grammatical THAN I
could understand it".

Do respond. I need a laugh and it seems you are ... well, not awake,
but posting. Are you drunk? Are you stoned?
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Jun 24 '06 #36

Richard Heathfield wrote:
sp*********@yahoo.com said:
Richard Heathfield wrote:
Andrew Poelstra said:
<snip>

> What, if anything, can it be guaranteed will be > '9' in standard C?

UCHAR_MAX + 1.0, I think, although if you have really amazingly colossal
chars you might manage to break it.
Do enlighten us, Richard. I was testing the character 9 which isn't the
highest value character,


The C Standard does not guarantee that. It's a minor point.
in ascii or unicode or even ebcdic.


Curiously, it /is/ the highest EBCDIC character with a well-defined meaning,
although it is certainly true that there are half a dozen slots above it.


And I should worry about EBCDIC? It is true, based on my experience in
teaching SAS C in 1989 that there are "C" compilers where you MIGHT get
away with your nonsense. The code for these compilers is NONPORTABLE to
ASCII machines as-is.

Which shows that in terms of modern languages there is literally no
such thing as the C programming language. It is an illusion.

And yet based on it you are conducting a campaign of personal and
professional libel.
Has your
favorite standard defined '9' as the perfect character?
No, but neither has it guaranteed that '9' is not the highest character.


Oh, ok, it MIGHT be the highest character therefore your wonderful code
can ignore the possibility (which the "might be" implies) that it is
not?
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Jun 24 '06 #37

pemo wrote:
sp*********@yahoo.com wrote:
Keith Thompson wrote:

It's still a good example of ugly C (they're called argc and argv,
not intArgCount and strArgValues), and it could probably be written
more
Nope, they are called what I called them. The abandonment of Hungarian
notation was a mistake.
I think Keith's comment on argc/argv is right, i.e., using argc/argv follows
the rule of keeping 'the least possible surprise value' to a minimium. It's
what's 'expected' - I feel that there's no good reason for changing the
parameter names, and doing so will only cause confusion somewhere down the
line.


The problem is that the use of a nonstandardizable and aliasing
language causes the confusion.

No generalization can be made world wide concerning the universality of
argc and argv. I've maintained code in Red China, and I am only amused
by these people in the USA who make unsupported generalizations about
what is "meaningful".

It's in the mind of the beholder. My OO style is delegation centric and
doesn't use enumerators (I need to change), I had to maintain code that
was inheritance and enum centric. I didn't charge the author with
incompetence, instead I endeavored to find out good reasons for change.

On Hungarian Notation, a few years ago [oh, now that I come to think about
it, that's quite a few years ago] I would have agreed with you - I used HN
all of the time, and liked it once I got used to it [I *had* to adopt their
use where I worked].

However, IMHO, modern development environments makes their use redundant -
At the time I wrote the code, I was thinking of coding in India on a
hand-cranked laptop without the power for a "modern development
environment".

In Hong Kong, a "modern development environment" costs 8000.00 HK
dollars. Why should be substitute money for thought and a
self-discipline?
now, if you want to know the type-of-something, its storage-class, or where
it's declared/defined - you simply use some shortcut/gesture built into the
development environment and you'll get all the information you need. And
that's great - this kind of feature, when used with meaningful names makes
code more readable [more easily parsable, and kinder on the eye]. In fact,
in dropping them, it might also make one think just a little harder about
the 'usage' part of any name used?
You may be missing the need for a structure in the name. The HN keeps
the name from being formally or informally reserved. It partitions the
"name space" into exclusive classes.

--
==============
*Not a pedant*
==============


Jun 24 '06 #38

sp*********@yahoo.com wrote: (in response to Richard Heathfield)
Are you for real? And you are sitting on your fat ass telling me I
don't know how to program?


It is evident from your code that you are not proficient with C,
so it is not necessary for Richard to comment on your ability.
However, your continual insistence that C is not suitable for new
development is incredibly annoying. C is certainly not
suitable for you, and you should either stop using it
or try to learn it. You clearly dislike Richard, but you
could probably learn a lot from him.

Jun 24 '06 #39

<sp*********@yahoo.com> wrote
Richard Heathfield wrote:
sp*********@yahoo.com said:
> Andrew Poelstra wrote:
>>
>> I stopped reading after the first function. I wasn't sure why he kept
>
> Which disqualifies you from a technical discussion.
No, it doesn't, because he can always go back and read it if he wishes.
And
he is certainly qualified to discuss the part he has read.
> Why are you posting?


Why are you?


Because you're engaged in a campaign of personal destruction as you
were with Schildt.

If you are going to argue that C is unusable for new development, on
comp.lang.c, then you can expect some pretty robust disagreement.

No, the mark of a bad programmer is inability to think outside the
particular set of chosen inputs and your insistence that C is still
usable for new development.

A function in C only has to be well-behaved for legal inputs. That's a
weakness in the language. Other languages have other weakness.
C offers no guarantee that there is any character with a code point
higher
than '9'. In EBCDIC, the code point of '9' is 249, so there are just six
characters (none with well-defined interpretations) with higher code
points. So Andrew's point is perfectly valid. It was also sufficiently
grammatical than I could understand it.
OK, this is complete nonsense. Are you pulling my leg?

You read in the standard that "C offers no guarantee with a code
point..."

But it MEANS that there CAN be. Can you read?

What it means is that the code

char ch = '9' + 1;

is allowed to break on a conforming implementation.
Now this isn't a particularly sensible rule, since as you say all the world
uses ASCII. But it is the rule. Code that doesn't adhere to it is not
strictly portable.

There are certain problems in converting between characters and the
underlying integers. Generally you want to keep a distinction between
natural language letters and integers, but for some purposes we do need a
number assciated with a letter, for instance when using letters for
indexing. In practise C does a reasonable job of this, though the theory is
a bit shaky.

--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jun 24 '06 #40
sp*********@yahoo.com wrote:
pemo wrote:
sp*********@yahoo.com wrote:
Keith Thompson wrote:

It's still a good example of ugly C (they're called argc and argv,
not intArgCount and strArgValues), and it could probably be written
more

Nope, they are called what I called them. The abandonment of Hungarian
notation was a mistake.
I think Keith's comment on argc/argv is right, i.e., using argc/argv follows
the rule of keeping 'the least possible surprise value' to a minimium. It's
what's 'expected' - I feel that there's no good reason for changing the
parameter names, and doing so will only cause confusion somewhere down the
line.


The problem is that the use of a nonstandardizable and aliasing
language causes the confusion.

No generalization can be made world wide concerning the universality of
argc and argv. I've maintained code in Red China, and I am only amused
by these people in the USA who make unsupported generalizations about
what is "meaningful".

Do the people in Red China use compilers where 'main' isn't named 'main'[*]?

To C programmers around the world, "int main(int argc, char *argv[])" (with
some minor variations) is an idiom, regardless of their native language.

I could see how a Chinese programmer might choose to forego the idiom and
name the arguments something else, but even that Chinese programmer would be
acting foolishly. 'argc' would be a better choice than any name in your
native language that means "integer representing the number of program
arguments", just as "#define AND &&" isn't better than just remembering what
logical conjunction is in C.
[*] They probably do have compilers that allow you to set the program entry
point yourself for circumstances where a traditional 'main' doesn't make
sense (freestanding environments, mostly), but this is orthogonal to my point.

S.
Jun 24 '06 #41
sp*********@yahoo.com schrieb:
Richard Heathfield wrote:
sp*********@yahoo.com said:
Andrew Poelstra wrote:

I stopped reading after the first function. I wasn't sure why he kept

Which disqualifies you from a technical discussion.
No, it doesn't, because he can always go back and read it if he wishes. And
he is certainly qualified to discuss the part he has read.
Why are you posting?


Why are you?


Because you're engaged in a campaign of personal destruction as you
were with Schildt.


IMO, it was not wise of Richard to post here before discussing
the matter with you via e-mail -- but I think so only for the
reason that you mentioned his name on the webpage under discussion.

It is certainly not wrong to highlight examples of particularly
wrong statements and low quality code.

I do not know about any special relationship between Richard
Heathfield and Herbert Schildt but after having read a fairly
recent book of his a couple of years ago, I developed the
opinion that his books are dangerously off the mark -- without
"help" by the community let alone Richard Heathfield.

If I were you, I'd do the smart thing and ask for a code review
around here. Put a corrected version up on your page -- it will
still illustrate part of your point but not leave you open to
the justified criticism that you provided a particularly bad
piece of code to illustrate it.

casting chars to ints, as though there wasn't implicit casting going on
by default. Then he tested for > '9', which made no sense to me.
Realizing that I wouldn't be able to trace that logic, I stopped.
<snip>You stopped trying to understand things twice, so your opinion is
worth...what?


Plenty. What he's saying is that your code is unnecessarily obscure and
difficult to read. That's the mark of a bad programmer, unless your intent
is to win the IOCCC.


No, the mark of a bad programmer is inability to think outside the
particular set of chosen inputs and your insistence that C is still
usable for new development.


Well, your code would not pass code review in any company I ever
worked for -- and not because of "small stuff".
This reflects bad on your qualification to harp on about C being
best dead and gone "as a professional".
I think that C is not the first choice for many tasks but will
continue to be used for new development in certain areas for a
long time. If you happen to work in another area, then you can
consider C as not being your first, second, third, or even tenth
choice.

<snip> Do respond. I need a laugh and it seems you are ... well, not awake,
but posting. Are you drunk? Are you stoned?


Considering the quality of your comments, I can understand why
Richard did not bother to contact you via e-mail first.
--

<snip>
Could you please stop quoting signatures?
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jun 24 '06 #42
Andrew Poelstra wrote:
.... snip ...
What, if anything, can it be guaranteed will be > '9' in standard C?


I don't know, but:

unsigned int ch;

if (((ch = getchar()) - '0') > 9) {
/* ch is not a digit */;
}
else {
/* ch is a digit */;
}

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

Jun 24 '06 #43
sp*********@yahoo.com wrote:
..... What puzzles me is the implication elsewhere
that if two strings appear, either adjacently or on separate lines,
they will be magically concatenated as in rexx. You may be right.


Actually, they are magically concatenated as in C. ;)
(Thanks for the rexx info anyhow)

From ISO/IEC 9899:1999

5.1.1.2 Translation Phases
....
6. Adjacent string literal tokens are concatenated.

7. White-space character separating tokens are
not longer significant. ...

Jun 24 '06 #44
sp*********@yahoo.com writes:

CC: sp*********@yahoo.com, which I'm assuming is Edward G. Nilges.
This is spinoza1111 who is Edward G. Nilges, author of Build Your Own
.Net Language and Compiler [and please, don't use C, thank you very
much.]

yes indeed and you write the same bloody wrong code as you always did
and your arguments havn't got better voer time.


I abandoned C shortly thereafter because each time I realized a new
deficiency, a new source of undefined behavior, I would write a
preprocessor macro or similar tool to encapsulate the cure.

Yeah you solution is hiding bade coding behind Macros, that's nothing
new to the regulars.

I bet this threads will not end before 500 posts, you blaming C for
every fault it allows you, other in pointing out that you have no clue
about C programming.

Friedrich

--
Please remove just-for-news- to reply via e-mail.
Jun 24 '06 #45
In article <-b********************@bt.com>,
Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291


I somehow missed the author's name at the top of the -- entry?
article? post? -- but well before I got to the actual code
I had made a guess that proved to be correct. The man does have a
distinctive style (though probably it was a major clue that it's
you drawing people's attention to the entry).

The use of macros seems somewhat C-idiomatic, but not the names
chosen for the arguments to main. (Who else .... ) I'm not sure
what to make of string2number, but perhaps there's a good reason
I'm not thinking of to not use one of the library functions (e.g.,
atoi or strtol) that would seem to accomplish the same thing.

--
B. L. Massingill
ObDisclaimer: I don't speak for my employers; they return the favor.
Jun 24 '06 #46
Richard Heathfield wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291

This "teacher of C" demonstrates his prowess with a masterful display of
incompetence in a 200-line program that travels as swiftly as possible to
Segfault City.

(Actually, using my normal gcc switches, it doesn't even get past TP3, but
it will at least compile if you just use gcc -o foo foo.c, after hacking it
around a bit to do things like mending the line-spanning single-line
comments and string literals, which - in fairness to the author - are
probably an artifact of the Webification of the code.)

I wonder how long I'll take to stop laughing.


It compiled cleanly with Digital Mars, Pelles C and lcc-win32.
Errors for missing or misplaced braces just after the first "if"
block in main()with Open Watcom. In the cases where it compiled,
it ran without a segfault.

In any event, the output is ponderous and confusing and there is
far too much superfluous code: the core code for the Sieve of
Eratothenes can be written in about a half dozen lines of C.

JS
Jun 24 '06 #47
In article <yv********************@bt.com>,
Richard Heathfield <in*****@invalid.invalid> wrote:
sp*********@yahoo.com said:

Andrew Poelstra wrote:
[ snip ]
What, if anything, can it be guaranteed will be > '9' in standard C?


This isn't grammatical therefore I do not fully understand it. If you
are saying there is no character greater than 9, well I wish you all
the best in your future career. You'll need it.


C offers no guarantee that there is any character with a code point higher
than '9'. In EBCDIC, the code point of '9' is 249, so there are just six
characters (none with well-defined interpretations) with higher code
points. So Andrew's point is perfectly valid. It was also sufficiently
grammatical than I could understand it.


I think if you parse the "What, if anything" sentence just so, it's
perfectly grammatical, though it does read a bit strangely.

--
B. L. Massingill
ObDisclaimer: I don't speak for my employers; they return the favor.
Jun 24 '06 #48
In article <-b********************@bt.com>,
Richard Heathfield <in*****@invalid.invalid> wrote:
[X-posted, and followups set]

I found something interesting on the Web today, purely by chance.

It would be funny if it weren't so sad. Or sad if it weren't so funny. I'm
not sure which.

http://www.developerdotstar.com/community/node/291


Something I wondered about was why the code tests numbers up through
half the highest value (call it N), rather than up through sqrt(N),
which is clearly (?) sufficient. Most discussions I've read of this
algorithm stop at sqrt(N), though perhaps the original algorithm
didn't?

--
B. L. Massingill
ObDisclaimer: I don't speak for my employers; they return the favor.
Jun 24 '06 #49
sp*********@yahoo.com said:
Richard Heathfield wrote:
sp*********@yahoo.com said:
<snip>
> Why are you posting?
Why are you?


Because you're engaged in a campaign of personal destruction as you
were with Schildt.


The important thing is that C students learn how to write C properly. The
characteristic you share with Schildt is that you are endeavouring to teach
C without actually knowing it, and /that/ is what is destructive.

<snip>
>
> You stopped trying to understand things twice, so your opinion is
> worth...what?


Plenty. What he's saying is that your code is unnecessarily obscure and
difficult to read. That's the mark of a bad programmer, unless your
intent is to win the IOCCC.


No, the mark of a bad programmer is inability to think outside the
particular set of chosen inputs


That's another mark, it's true, but my point is still perfectly valid.
and your insistence that C is still usable for new development.
Well, that's certainly an opinion, although I doubt whether it will be
shared by many here in comp.lang.c.
>> What, if anything, can it be guaranteed will be > '9' in standard C?
>
> This isn't grammatical therefore I do not fully understand it. If you
> are saying there is no character greater than 9, well I wish you all
> the best in your future career. You'll need it.


C offers no guarantee that there is any character with a code point
higher than '9'. In EBCDIC, the code point of '9' is 249, so there are
just six characters (none with well-defined interpretations) with higher
code points. So Andrew's point is perfectly valid. It was also
sufficiently grammatical than I could understand it.


OK, this is complete nonsense. Are you pulling my leg?


No, I'm perfectly serious, and no, it's not even incomplete nonsense, let
alone complete nonsense. What I have said is accurate.
You read in the standard that "C offers no guarantee with a code
point..."
Not those exact words, but yes, it's true that the Standard offers no such
guarantee.
But it MEANS that there CAN be. Can you read?
Yes, I can read, and yes, there can be characters with a higher code point.
And to use EBCDIC, a completely obsolete encoding, obsoleted by ASCII
and then international 16 bit encoding...the mind boggles!
Some programmers don't get to choose their character set.
In ASCII, for which nearly all C code is written, the letters follow
the numbers! If the user enters A your "correct code" breaks?
Not at all. But to rely on the letters following the numbers (which, I
hasten to add, your code does not) would be silly.
[The "standard" may require the C runtime to treat the digits as
following the characters.
It doesn't. The guarantees given by the Standard w.r.t. code points are as
follows:

1) all characters in the basic source and execution character sets have
positive values;
2) '0' to '9' are in numerical order and contiguous.
The fact is that real compilers don't, and
use the encoded value. What this illustrates is the UNUSABILITY of the
standard, and consequently that it is extremely unwise, to the level of
professional malpractice, to recommend C for new development, as you
appear to.]
No, it illustrates that you don't understand the Standard's guarantees about
code points (see above).
Are you for real? And you are sitting on your fat ass telling me I
don't know how to program?
Well, I don't own a donkey, fat or otherwise, but apart from that you're
broadly correct, yes.
But then you say that there are "just 6 characters" as if the small
number of characters makes it probable that your code won't break!
No, I'm saying that to rely on character ordering that is not guaranteed by
the Standard renders code non-portable to systems where that reliance is
misplaced. I will again say, however, that your code does *not* fall foul
of this particular issue. We are discussing a minor point raised by Andrew
about a curious way of phrasing a character test, not an error in your
code.
"My program is standard C, therefore the user has no right to send
characters with t a value higher than 9" is the zenith of arrogance.
But nobody is saying that.
And you use this as a reason for presenting code which BREAKS if there
IS a code point after all (c - 0 with no test for greater than 9)????
Not at all.
This is worse than I thought.

You seem to be using C on an IBM mainframe with the SAS compiler, and
pompously talking about C based on a misreading of the standard!
Please cite and explain the relevant section of the Standard that you think
I am misreading.
And if your compiler runs on an ASCII system, it has to jiggle
characters at runtime to make sure 9 is the "last" character.
No, not at all. You seem to have misunderstood my point completely.
And C is an "efficient" language?
No, C is a programming language. Whether C programs are efficient depends on
how they are written. It is easily possible to write inefficient programs
in C, just as it is easily possible to write inefficient programs in any
sufficiently powerful programming language. (The caveat is only there
because I suppose it is possible to conceive of a programming language so
limited that all its expressible programs are efficient, but that would
almost certainly be a very limited language indeed.)
Without being even aware that given aliasing, C can't be standardized
in a modern sense?
Well, I'll let you take that up with ISO.
And icing on the cake..."it was also sufficiently grammatical THAN I
could understand it".

Do respond. I need a laugh and it seems you are ... well, not awake,
but posting. Are you drunk? Are you stoned?


No, but I am in the mood to write a Sieve. See below.
First, though, I'll recompile your program to allow writeable strings, and
see what it tells me:

me@here:~/scratch> ./foo 1 10 10
Sieve of Eratosthenes primes from least prime >= 3 to greatest prime <= 10
Sieve contains 10 entries
3
Sieve contains 134520391 entries
5
Sieve contains 134520391 entries
7
Sieve contains 134520391 entries
Number of primes found: 3
Number of nonprimes found using the sieve: 1
Number of nonprimes found using brute force: 0
Number of primes in the sieve: 3
Number of primes displayed: 3
Time in approximate seconds: 0

Curious how the sieve expands suddenly, isn't it?

Incidentally, changing the sieve size to 100000, I get a runtime (as
measured by time(1)) of 5.8 seconds with output redirected to /dev/null (to
eliminate console updating, which is slow). With a sieve size of 1000000,
the runtime is positively chelonian, and I canned it after about 7 minutes.

Here are some comparative performance statistics:

Max Execution time (seconds, excluding display)
prime
value My program Your program
10 0.003 0.002
100 0.003 0.002
1000 0.003 0.003
10000 0.004 0.081
100000 0.014 5.808
200000 0.017 20.102
300000 0.024 46.097
400000 0.060 too long

And here's my program, which, in the interests of fairness, I have made 200
lines long:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <time.h>
#include <math.h>

#define DEFAULT_SIEVE_BYTES 1024UL
#define DEFAULT_SIEVE_SIZE (DEFAULT_SIEVE_BYTES * CHAR_BIT)

/* Bitmapping macros */

#define BYTE(array, bit) ((array)[(bit) / CHAR_BIT])
#define MASK(bit) (1 << ((bit) % CHAR_BIT))
#define SET_BIT(array, bit) \
BYTE(array, bit) |= MASK(bit)
#define CLEAR_BIT(array, bit) \
BYTE(array, bit) &= ~MASK(bit)
#define TEST_BIT(array, bit) \
(!!(BYTE(array, bit) & MASK(bit)))

/* Helper function prototypes */
void show_help(void);
void do_sieve(unsigned long first, unsigned long last);
void sort_two_uls(unsigned long *a, unsigned long *b);

/* program entry point */
int main(int argc, char **argv)
{
int rc = EXIT_SUCCESS;

/* start the clock */
time_t start = time(NULL);

/* capture and crop limits */
if(argc > 2)
{
char *end1 = NULL;
char *end2 = NULL;
unsigned long first = strtoul(argv[1], &end1, 10);
unsigned long last = strtoul(argv[2], &end2, 10);
sort_two_uls(&first, &last);
if(end1 == argv[1] || end2 == argv[2])
{
show_help();
fprintf(stderr,
"Invalid argument %s\n",
end1 == argv[1] ? end1 : end2);
rc = EXIT_FAILURE;
}
else if(last < 2)
{
printf("Trivial case - no primes in list.\n");
rc = EXIT_FAILURE;
}
else
{
/********************
* All is well. *
* Go do the sieve! *
********************/

do_sieve(first, last);
}
}
else
{
show_help();
rc = EXIT_FAILURE;
}
if(rc == EXIT_SUCCESS)
{
/* Stop the clock and display the runtime */
time_t end = time(NULL);
fprintf(stderr,
"Approximate execution time (seconds): %.0f\n",
difftime(end,
start));
}
return 0;
}

void do_sieve(unsigned long first, unsigned long last)
{
unsigned long candidate = 0;
unsigned long root = 0;
unsigned long scratch = 0;
unsigned long primes = 0;

unsigned char default_sieve[DEFAULT_SIEVE_BYTES] = {0};
unsigned char *sieve = default_sieve;
if(last > DEFAULT_SIEVE_SIZE)
{
size_t bytes = last / CHAR_BIT + 1;
sieve = calloc(bytes, sizeof *sieve);
if(sieve == NULL)
{
fprintf(stderr,
"I can't build a sieve that big.\n"
"I'm using the default sieve size\n"
"(which is %lu) instead. Sorry.\n",
DEFAULT_SIEVE_SIZE);
sieve = default_sieve;
last = DEFAULT_SIEVE_SIZE;
if(first > last)
{
first = last / 2;
fprintf(stderr,
"That means I have to adjust\n"
"the range as well. I am now\n"
"using the range %lu - %lu\n",
first, last);
}
}
}

/* OKAY! We can now use our sieve. At present, it
* is populated entirely with zero-bits. We will
* take 0 to mean "might be prime", and 1 to mean
* "is definitely not prime". At the end of the
* process, of course, 0 will mean "IS prime".
*/

/* find the root of the upper limit */
root = sqrt(last) + 1;

/* Mark 0 and 1 as being non-prime */
SET_BIT(sieve, 0);
SET_BIT(sieve, 1);

/* Mark 4 as non-prime */
SET_BIT(sieve, 4);

/* Mark all numbers of the form 6n, 6n + 2, 6n + 3
* and 6n + 4 as being non-prime.
*/
for(candidate = 6; candidate <= last; candidate += 6)
{
SET_BIT(sieve, candidate);
SET_BIT(sieve, candidate + 2);
SET_BIT(sieve, candidate + 3);
SET_BIT(sieve, candidate + 4);
}

for(candidate = 5; candidate <= root; candidate += 2)
{
for(scratch = candidate * 2;
scratch <= last;
scratch += candidate)
{
SET_BIT(sieve, scratch);
}
}

for(candidate = first; candidate <= last; candidate++)
{
if(!TEST_BIT(sieve, candidate))
{
printf("Prime found: %lu\n", candidate);
++primes;
}
}

fprintf(stderr, "Total primes found: %lu\n", primes);

if(sieve != default_sieve)
{
free(sieve);
/* help to protect against maintenance errors */
sieve = NULL;
}
return;
}

void show_help(void)
{
const char *help[] =
{
"\n This program uses Eratosthenes' Sieve to work\n",
" out all the primes between two limits. Please\n",
" run the program again, specifying both limits.\n\n",
NULL
};
int i = 0;
do
{
fputs(help[i++], stderr);
} while(help[i] != NULL);
return;
}

void sort_two_uls(unsigned long *a, unsigned long *b)
{
if(*a > *b)
{
unsigned long t = *a;
*a = *b;
*b = t;
}
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 24 '06 #50

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

Similar topics

12
by: Nathaniel Echols | last post by:
I've written a function in C to perform protein sequence alignment. This works fine in a standalone C program. I've added the necessary packaging to use it in Python; it returns three strings and...
11
by: H.A. Sujith | last post by:
The following code is causing a segfault at the first if statement. Am I doing something wrong or is it a compiler bug? //---------- #include <stdio.h> int main(int argc, char *argv) { int...
10
by: name | last post by:
When I started testing the algorithms for my wrap program, I threw together this snippet of code, which works quite well. Except that it (predictably) segfaults at the end when it tries to go...
165
by: Dieter | last post by:
Hi. In the snippet of code below, I'm trying to understand why when the struct dirent ** namelist is declared with "file" scope, I don't have a problem freeing the allocated memory. But...
7
by: spinoza1111 | last post by:
"segfault city" was an interchange wherein Richard Heathfield posted a complete lie: <heathfield> Richard Heathfield wrote: > This would be a straightforward test for numerics: > > int...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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
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,...

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.