PDA

View Full Version : Fun with C


BenBurch
27th June 2009, 08:26 AM
My favorite way to code an infinite loop in C;


#include <stdio.h>

#define ever (;;)

int main()
{
for ever
{
printf("Aleph-null bottles of beer on the wall.\r\n");

}
}


Anybody else have any fun C stuff?

asmodean
28th June 2009, 03:35 AM
Perhaps not a pretty piece of code, but can be useful to determine wether your compler uses old k&r unsigned preserving sematics or the standard value preserving


if (-1 < (unsigned char)0)
puts("Value preserving\n");
else
puts("Unsigned preserving\n");


If old K&R semantics, the nsignedc char will be widened, but the unsignedness kept, the -1 will be unsigned as well, since with tis semantics mixing signed and unsigned will "promote" both sides to unsigned, thus making -1 a rather large, unsigned quantity that is much larger than 0.

In ANSI value preserving is used, so under the normal integral promotions the -1 and 0 will both be promoted to int (since both values will fit in an int), no arithmetic conversions needed and you'll get the expected result, -1 is less than 0.

Perhaps not such a big issue in modern environments but if one maintains code on legacy systems it may come in handy.

I am also very fond of the HAKME bit counter for 32 bit unsigned integers:


int bitcount(unsigned int n)
{
register unsigned int tmp;

tmp = n - ((n >> 1) & 033333333333)
- ((n >> 2) & 011111111111);
return ((tmp + (tmp >> 3)) & 030707070707) % 63;
}


basicaly work from an octal representation, that is each group of 3 is "worth" 4A + 2B + C

divide this by 2 (right shift one) and subtract and, further divide by 4 (RS 2 steps) and subtract and you'll get:

4A + 2B + C - (2A + B) - A = A+B+C

which is the number of bits in the original octal digit. Then just add adjascent bit count groups together, i.e

0x32323232 => tmp = 0x1124a211 = 00 010 001 001 001 001 010 001 000 010 001

tmp = (tmp + tmp >> 3) =>

00 010 001 001 001 001 010 001 000 010 001
00 000 010 001 001 001 001 010 001 000 010
=>
00 010 011 010 010 010 011 011 001 010 011 =

0043444344123 (octal) the top 2 bits does not contain anything of value, skipping the first group (the addition is not made there), then check every second group it is obvious that these contains the summation of adjascent bit count groups. Mask out the un needed stuff:

00 010 011 010 010 010 011 011 001 010 011 &
11 000 111 000 111 000 111 000 111 000 111 (030707070707)
=>
00 000 011 000 010 000 011 000 001 000 011

The result is basically groups if 6 bits containing the count of set bits in the corresponding 6 bits set in the original number

00 000011 000010 000011 000001 000011
00 110010 001100 100011 001000 110010 (n = 0x32323232)

Take this result (tmp) and do a modulus 63, which will neatly give the added result:

00 000011 000010 000011 000001 000011 % 63 => 12

which is the # of set bits in the original integer n. I just love this piece of code, whoever came up with it is a freaking genious. :)

Of course, if you're on an architecture lacking / operator in the silicon, one might want to just mask out and add the groups together in one go rather than fiddle with % operator.

moopet
28th June 2009, 06:21 AM
Well, I've always said I'd like exit(0); on my gravestone.

a_unique_person
28th June 2009, 06:42 AM
The title of this thread is an oxymoron. :duck:

asmodean
28th June 2009, 07:08 AM
Well, I've always said I'd like exit(0); on my gravestone.

That or:


kill(getpid(), SIG_KILL);

or maybe:

His Last Words:
"Screw best practice, how bad can one small goto really be?"

asmodean
28th June 2009, 07:10 AM
The title of this thread is an oxymoron. :duck:

Hey, the only thing funnier than coding in a language with more sections undefined or implementation defined than actually defined features, is to tap dance in a mine field wearing a blindfold. :p

moopet
28th June 2009, 07:43 AM
The title of this thread is an oxymoron. :duck:

It's a tautology!

realpaladin
28th June 2009, 07:51 AM
Well, I've always said I'd like exit(0); on my gravestone.

Even when you have been horribly mangled by a big cement truck that fell down the bridge because it swerved to avoid an ambulance that took the wrong turn after it had just loaded up on a preacher that wanted to demonstrate that the piece of toast with the image of Jezus told him that he could walk the pacific ocean even though he could not swim?

In my eyes that *would* warrant at least an exit(1);...

moopet
28th June 2009, 08:02 AM
Even when you have been horribly mangled by a big cement truck that fell down the bridge because it swerved to avoid an ambulance that took the wrong turn after it had just loaded up on a preacher that wanted to demonstrate that the piece of toast with the image of Jezus told him that he could walk the pacific ocean even though he could not swim?

In my eyes that *would* warrant at least an exit(1);...

Here lieth Ben Si$**kh81[[[[
Segmentation fault. Core dumped.

realpaladin
28th June 2009, 08:10 AM
Here lieth Ben Si$**kh81[[[[
Segmentation fault. Core dumped.
That's what you for playing with pointer "magic" :duck:

dasmiller
28th June 2009, 08:45 AM
This explains my general view of C:
http://www.asandler.com/jokes/computer/c.shtml

We stopped when we got a clean compile on the following syntax:

for(;P("\n"),R-;P("|"))for(e=C;e-;P("_"+(*u++/8)%2))P("|"+(*u/4)%2);

To think that modern programmers would try to use a language that allowed such a statement was beyond our comprehension!

Wudang
29th June 2009, 01:25 AM
Wudang's corollary to Clarke's Law "Any sufficiently advanced programming language is indistinguishable from line noise"

SezMe
29th June 2009, 01:35 AM
UCLA once required its MBA students to take a course in APL (http://en.wikipedia.org/wiki/APL_%28programming_language%29). It is a horribly unreadable language. I remember writing code that I couldn't read an hour later.

realpaladin
29th June 2009, 01:38 AM
UCLA once required its MBA students to take a course in APL (http://en.wikipedia.org/wiki/APL_%28programming_language%29). It is a horribly unreadable language. I remember writing code that I couldn't read an hour later.
Try writing code at a 'demo-party' whilst drinking a lot and 'smoking'... man, the next day you will find your code is brilliant, but you have not a single clue as to what it should do.

MRC_Hans
29th June 2009, 01:54 AM
The worst write-only languate I have ever worked with was Forth. Terrible compact, terribly effective, totally impenetrable.

I think I have temporarlily lost the edge, but I used to do some nifty C code. I have a prime-finder routine that manages to break almost all good programming practice rules in about ten lines :roll:

Hans

Wudang
29th June 2009, 02:18 AM
UCLA once required its MBA students to take a course in APL (http://en.wikipedia.org/wiki/APL_%28programming_language%29). It is a horribly unreadable language. I remember writing code that I couldn't read an hour later.

Real programmers don't write in Apl. Any fool can be obscure in Apl.
http://home.online.no/~wsaa/real.programmers.html

SezMe
29th June 2009, 03:10 AM
... and did. Thanks, Wudang. Good stuff.

BenBurch
29th June 2009, 03:42 AM
That's what you for playing with pointer "magic" :duck:

Core of a state machine based on pointers;


/*
deliver.c - deliver_event function

Author: Ben Burch
Date: October 3, 1990

Copyright � 1990 Ben Burch

This function calls the state machine pointer indicated by
state_machine_id in current_event. The return from this call
is the next state machine pointer for that state_machine_id.

*/
#include "event.h" /* define event structures */

#include "state.h" /* define state-related functions */

#include "SCORB.h"

#include <stdio.h>

extern EVENT current_event ;
extern long long SCORBtimestamp;

unsigned int event_logging = FALSE;
int log_file_open = FALSE;
FILE *log_file_fp;

void deliver_event ()
{
if( event_logging ) /* Warning! Logging will decrease performance! */
{
if( !log_file_open )
{
log_file_fp = fopen("/tmp/SCORBLOG.dat", "w" );
if ( log_file_fp == NULL )
{
perror ("SCORB::deliver() unable to open logging file :");
fatal();
}
else
{
log_file_open = TRUE;
}
}
fprintf(log_file_fp, "%8d, %8d, %08lx, %12lld\n", current_event.state_machine_id,
current_event.event_code, current_event.event_argument, SCORBtimestamp);
fflush(log_file_fp);
}
state_array[current_event.state_machine_id] =
(unsigned long (*)()) state_array[current_event.state_machine_id]() ;
}

MRC_Hans
29th June 2009, 03:47 AM
Pointers is what makes the tale of Hell probable :eek:. It seems to easy and elegant, but, 'here there be dragons.! One really nasty type of pointer caveat is the one that appears to return the right values most of the time.

Hans

asmodean
29th June 2009, 04:02 AM
Try writing code at a 'demo-party' whilst drinking a lot and 'smoking'... man, the next day you will find your code is brilliant, but you have not a single clue as to what it should do.

Been there, done that (minus the "smoking"). Drink, no sleep for 50+ hrs, and intense coding can make for an interresting ... reading experience once back to normal.

Have also, more than once in my university days,coded on the MUD I helped start while so drunk that I almost couldn't hit the keyboard. Made for some interresting quality time with the debugger later. :)

moopet
29th June 2009, 04:24 AM
Have also, more than once in my university days,coded on the MUD I helped start
Do tell, does it still run?

realpaladin
29th June 2009, 04:53 AM
Do tell, does it still run?
Now... while there's nobody here but us geeks... :D

Almo
29th June 2009, 04:53 AM
http://www.ioccc.org/

I particularly like this one:

http://www0.us.ioccc.org/1995/vanschnitz.c

It won "Worst Abuse of the C Preprocessor and Most Likely To Amaze"

This thing recursively and conditionally includes itself to generate a program that prints the solution to the Tower of Hanoi problem.

gcc hanoi.c -o hanoi -Dn=4

Is how you call it. n is the number of discs.

asmodean
29th June 2009, 04:58 AM
Do tell, does it still run?

Alas, it does not. I think there's some brave (some would say insane) souls out there running other MUDs based of our code. I dunno why, it was a horrible mess to be honest. Too many cooks and all that.

realpaladin
29th June 2009, 11:17 AM
Alas, it does not. I think there's some brave (some would say insane) souls out there running other MUDs based of our code. I dunno why, it was a horrible mess to be honest. Too many cooks and all that.

There has not been a single MUD run on this planet that was not called 'a steenkeeen mess in eets guts' :)

But that basically was the whole fun of MUD's; co-operative coding and modifying stuff in a live environment.

That is how we got our Faculty to sponsor us the hardware and the Internet-link... (I am telling my age now, am I?)

I Ratant
29th June 2009, 11:44 AM
The worst write-only languate I have ever worked with was Forth. Terrible compact, terribly effective, totally impenetrable.

I think I have temporarlily lost the edge, but I used to do some nifty C code. I have a prime-finder routine that manages to break almost all good programming practice rules in about ten lines :roll:

Hans
.
I tried some Forth many years back.
I actually liked it, but found better and easier ways to do things.
ISTR it being termed a "write once, read never" language.
I still have some Forth modules for my HP71C handheld computer.
And possibly for my HP41CV calculator. If memory serves...

realpaladin
29th June 2009, 11:49 AM
Forth... *brrrrrr*... was the first programming language I bought for my ZX... never again!
Went straight to assembly after that.

Molinaro
29th June 2009, 01:16 PM
UCLA once required its MBA students to take a course in APL (http://en.wikipedia.org/wiki/APL_%28programming_language%29). It is a horribly unreadable language. I remember writing code that I couldn't read an hour later.

I liked that language!

It's been a while since I've seen a keyboard with the APL characters on the front face of the keys.

BenBurch
29th June 2009, 01:25 PM
Forth... *brrrrrr*... was the first programming language I bought for my ZX... never again!
Went straight to assembly after that.

:-)

There is a language family Neon->MOPS->Yerk that is Object-oriented Forth, and which I got to be pretty good at.

Look it up some time.

Almo
29th June 2009, 07:24 PM
http://esolangs.org/wiki/Befunge

Befunge was designed specifically to defy compilation.

BenBurch
29th June 2009, 08:25 PM
Current MOPS implementation; http://powermops.com/

Terry
29th June 2009, 08:38 PM
: forth ." rules" ;

BenBurch
29th June 2009, 08:48 PM
: forth love if honk then ;

asmodean
30th June 2009, 12:22 AM
There has not been a single MUD run on this planet that was not called 'a steenkeeen mess in eets guts' :)

Thats true. And kinda fun to dig through the code after all is said and done and see how people have developed. One of the people with whom I originally started the whole ting with (we where 4) was a PASCAL programmer who wanted tolearn a bit of C. You can guess how that went in the beginning. =)

Then of course, we based ours of an existing code base (though, in the end I dont think there was an original system left that hadn't been completely rewritten), and that one was messyas hell to. No inclusion guards. Instead of the old definitions in oneh eader, declarations in one source file, include heade rwhere you whish to use functions/data every source file that wanted to use something did their own definition, and soon, and soon... horrible.

But that basically was the whole fun of MUD's; co-operative coding and modifying stuff in a live environment.

Agree. Sketch out a new piece of code. Hack it together, test it, hotboot the live server with the changes and see people use the stuff right off the bat.

except for the aforementioned drunk-enough-to-miss-keyboard coding sessions that is. =)

That is how we got our Faculty to sponsor us the hardware and the Internet-link... (I am telling my age now, am I?)

Geeze, old coot... :D

Never had to do that, our success was that we got the admins to officially allow us to run the mud on one of the new shiny IPX stations, giving us an mud-group and some minor admin stuff tomake sure things ran smoothly.

That the UN*X admin at that uni was something of a geek himself might have helped a lot with that though.

Bob Blaylock
30th June 2009, 12:40 AM
Anyone think that they can guess what language this is in, or what it does?

«
RCLF DEG
1 4 FOR i
5 ROLL '1_°' CONVERT
IF i 2 MOD 0 == THEN
NEG
END
NEXT
→ flags lat1 lon1 lat2 lon2
«
lat1 SIN lat2 SIN *
lat1 COS lat2 COS *
lon2 lon1 - COS * + ACOS
DUP '60_nmi' *
SWAP '1_°' CONVERT
→ d60
«
CASE
lat1 ABS '90_°' == THEN
lat1 '90_°' +
END

d60 '0_°' == THEN
'0_°'
END

d60 '180_°' == THEN
'0_°'
END

@DEFAULT@
lat2 SIN lat1 SIN
d60 COS * -
d60 SIN lat1 COS * /
ACOS '1_°' CONVERT
IF lon2 lon1 - SIN 0 ä THEN
'360_°' SWAP -
END
@END@
END
SWAP
»
flags STOF
»
IF DUP '0.1_mi' < THEN
'1_ft'
ELSE
'1_mi'
END
CONVERT
»

CynicalSkeptic
30th June 2009, 01:28 AM
This explains my general view of C:
http://www.asandler.com/jokes/computer/c.shtml

" the Unix operating system and C programming language created by them is an elaborate April Fools prank kept alive for over 20 years" Uhh, how old is that article? Nice touch that it lists the day & month, but not the year.

SezMe
30th June 2009, 02:00 AM
Thats true. <snip>
The number of typos, etc. in that post suggest you were lit while posting.

asmodean
30th June 2009, 03:26 AM
The number of typos, etc. in that post suggest you were lit while posting.

Hmm, well...it is a nice summer, vacation in full swing... So. No comment. I deny everything. :D

ddt
30th June 2009, 03:57 AM
We're talking about write-only languages and nobody mentioned Perl? :jaw-dropp


I think I have temporarlily lost the edge, but I used to do some nifty C code. I have a prime-finder routine that manages to break almost all good programming practice rules in about ten lines :roll:
Ten lines? How about one:
(1x$_)!~/^(..+)\1+$/&&print"$_\n"for 2..<>

Regular expressions rock :D

dasmiller
30th June 2009, 06:41 AM
" the Unix operating system and C programming language created by them is an elaborate April Fools prank kept alive for over 20 years" Uhh, how old is that article? Nice touch that it lists the day & month, but not the year.

It took a little digging, but it seems to have come out in June 1991. That sounds about right to me.

Molinaro
30th June 2009, 08:14 AM
Anyone think that they can guess what language this is in, or what it does?


It looks like it was written for one of those old HP programmable calculators.

Here_to_learn
30th June 2009, 11:53 AM
Real programmers...No Real Programmers discussion can be complete without the story of Mel (http://www.cs.utah.edu/~elb/folklore/mel.html).


Regarding C - when i was doing tech support to programmers for an Intel Unix dialect we had a customer calling us up to tell us that the open() call was broken. We tried to argue that it would be hard for the OS to even boot without open(), but they insisted.

Finally it was agreed that I would go on site to try to find out what was going on, and if I could prove that it was their code that was broken they would pay for my time.

Of course it turned out that the fault was in their code - incrementing a struct pointer and writing to the resulting address, without understanding the type of the pointer. They assumed it would step one byte forward, when of course it stepped forward outside of the struct.

Adding some casts of course made the code even more unreadable, but hey - it worked.

jnelso99
30th June 2009, 11:56 AM
It looks like it was written for one of those old HP programmable calculators.

Looks like it to me. Now I want to find one of my HP-48s and plug the program in...

I Ratant
30th June 2009, 11:58 AM
I had to debug a BASIC program used in Flight Test to look at real-time information on the airplane while it was flying one day!
The guy that wrote the program jumped out of a subroutine to the next stage of the program, rather than terminate the subroutine and then go to the next stage.
Do this 10 times, and the program locks up.
Finding it in code I'd never seen before was interesting, while all that money was being burnt. :)

BenBurch
30th June 2009, 12:34 PM
BASIC for real time flight test. That was the first error.

realpaladin
30th June 2009, 12:38 PM
Ok... this needs to be done... sorry...

10 poke 808,255
20 print "RealPaladin was here!"
30 goto 20

CynicalSkeptic
30th June 2009, 01:12 PM
It took a little digging, but it seems to have come out in June 1991. That sounds about right to me.

Looks about right based on the web page it's on.

I Ratant
30th June 2009, 01:30 PM
BASIC for real time flight test. That was the first error.
.
Whatcha gonna do in 1985?
The main frame computers weighed more than the airplane!

moopet
30th June 2009, 01:31 PM
I had to debug a BASIC program used in Flight Test to look at real-time information on the airplane while it was flying one day!
The guy that wrote the program jumped out of a subroutine to the next stage of the program, rather than terminate the subroutine and then go to the next stage.
Do this 10 times, and the program locks up.
Finding it in code I'd never seen before was interesting, while all that money was being burnt. :)

"Can anybody fly a plane? And code BASIC?"

Almo
30th June 2009, 03:09 PM
I bet these guys' code (http://www.mud.co.uk/) is clean.

I Ratant
1st July 2009, 10:02 AM
"Can anybody fly a plane? And code BASIC?"
.
It wasn't a multi-task environment.
There were skilled airplane drivers up front, fussy aeronautical engineers in the back looking at the computer output, and the instrumentation guy who changed the flight tape every two hours.
That was me.
I'd taught myself BASIC, and was continually amazed at the spaghetti code or just plain obtuse methods the guys that had been through the HP course came up with.
Such as seeing "?" on the screen.
What did that want the user to do?
Adding an explanatory note didn't occur to the guy that wrote the program, he knew what the program needed for that "?"... and the next, and the next.. even though there was the LINE INPUT command. I guess typing INPUT took less energy when writing the program. Didn't have to think up a prompt.
And filling data arrays one column at a time, when with a little nesting all the rows of data could be input in a sensible sequence.
One of the guys came up with a 4 page program to print labels for the flight tapes.
I cut that down to 60 lines.
Nowadays, I find there's Windoze programs that do what I want to do, the way I want to do it, most of the time, but they're incredibly bloated monsters, obviously no concern about memory availability, so I haven't felt any urge to program anything in years.
Haven't done any LISP for AutoCad in years. I had a few that would do some tasks so simply..
Wrote a program to display the orbits of the Galilean satellites in RPN on my HP41CV. I wonder if that even works any more..

Bob Blaylock
1st July 2009, 12:38 PM
Anyone think that they can guess what language this is in, or what it does?

«
RCLF DEG
1 4 FOR i
5 ROLL '1_°' CONVERT
IF i 2 MOD 0 == THEN
NEG
END
NEXT
→ flags lat1 lon1 lat2 lon2
«
lat1 SIN lat2 SIN *
lat1 COS lat2 COS *
lon2 lon1 - COS * + ACOS
DUP '60_nmi' *
SWAP '1_°' CONVERT
→ d60
«
CASE
lat1 ABS '90_°' == THEN
lat1 '90_°' +
END

d60 '0_°' == THEN
'0_°'
END

d60 '180_°' == THEN
'0_°'
END

@DEFAULT@
lat2 SIN lat1 SIN
d60 COS * -
d60 SIN lat1 COS * /
ACOS '1_°' CONVERT
IF lon2 lon1 - SIN 0 ä THEN
'360_°' SWAP -
END
@END@
END
SWAP
»
flags STOF
»
IF DUP '0.1_mi' < THEN
'1_ft'
ELSE
'1_mi'
END
CONVERT
»


It looks like it was written for one of those old HP programmable calculators.


Looks like it to me. Now I want to find one of my HP-48s and plug the program in...


Yes. I wrote it for an HP48G. So what does it do?

jnelso99
1st July 2009, 12:58 PM
Some kind of great circle distance calculation?