Nihilistic programming

Status
Not open for further replies.

pelican

Wise, Aged Ars Veteran
184
code:<HR>
Code:
function meta_associate_select_edit($selectname, $database, $parent_table, $child_table, $link_table, $parent_field_select, $parent_field_id, $parent_link_field, $child_link_field, $id, $size) {
	database_connect("$database");
	$query = "SELECT $child_link_field FROM $link_table WHERE $parent_link_field='$id'";
	$result = mysql_query($query);
	$query2 = "SELECT $parent_field_id, $parent_field_select FROM $parent_table";
	$result2 = mysql_query($query2);
	$selected_list = array();
	$i = 0;
	while (list($cid) = mysql_fetch_row($result)) {
		$selected_list[$i] = $cid;
		$i++; }
	echo "<select name=\"$selectname\" multiple size=\"$size\">";
	while(list($CID, $SELECT) = mysql_fetch_row($result2)) {
		$str = "<option value=\"$CID\"";
		foreach($selected_list as $temp) {
		if ($CID == $temp) { $str .= " selected"; }
		}
		$str .= ">$SELECT</option>";
		echo $str; }
	echo "</select>";
	}

Okay, okay, so we all do this sometimes: I found this little beauty deep, far inside of an application I wrote in 4 hours. Ooops. I was hoping no one would _ever_ have to read it, and guess who ended up reading it: me.

So post your own - let's see the worst code we've all written. It doesn't matter if you can't remember why: heck, it's better.

Cheers,
--pelican
 

Ezran

Wise, Aged Ars Veteran
137
Here's a gem from some stuff I did for work a couple summers ago:

code:<HR>
Code:
  $input =~ s/<xml>.+?<\/xml>//sig;
  $input =~ s/<(o|w):[^>]+>[^<]*<\/(o|w):[^>]+>//ig;
  $input =~ s/mso-[^:;'"]+:"?[^;'"]+"?(;|(?=['"]))//ig;
  $input =~ s/[\r\n]\s*[\r\n]/\n/g;
  $input =~ s/<p\s+[^>]+>(\s*<(?!a[\s\r\n])[^>]+>){1,}\ (\s*<(?!a[\s\r\n])[^>]+>){1,}<\/p>/
/ig;
  
  @allpolicies = ();
  %foundpolicies = ();
  while ($input =~ /<a[^>]+name\s*=\s*"?p(\d+)/ig) {
    push @allpolicies, $1;
  }
  
  $futureset = $futureset1 = $futureset2 = $input;
  foreach $pol (@allpolicies) {
    if ($futureset =~ /<p\s+[^>]+>([^<]*<(?!(a|p|br)[\s\r\n])[^>]+>){0,}?[^<]*<a[^>]+name\s*=\s*"?p$pol"?[^>]*>.+?($|(?=<a[^>]name\s*=\s*"?p\d+))/si) {
      $foundpolicies{$pol} = $&;
      $futureset = $futureset1;
      $futureset1 = $futureset2;
      $futureset2 = $';
    }
  }
  
  foreach $pol (@allpolicies) {
    if (!defined $foundpolicies{$pol}) {
      if ($input =~ /(<[^\/>][^>]+>\s*){0,}<a[^>]+name\s*=\s*"?p$pol"?[^>]*>.+?($|(?=<a[^>]name\s*=\s*"?p\d+))/si) {
        $foundpolicies{$pol} = $&;
      } else {
        print "<font color=\"red\">Policy $pol not found.  Please check the bookmarks for this policy.</font>
\n";
      }  
    }
  }

-- Ezran
 

Ezran

Wise, Aged Ars Veteran
137
Originally posted by ix_wookiee:
count so far :
perl : 2
everything else : 0

Well, we're certainly going to have to correct that.

If you look more carefully, the first code sample is PHP, not Perl.

I have written some ugly stuff in C++ as well, but the regular expressions in this one particular Perl script take the cake. They are for reformatting and parsing HTML files generated by Microsoft Word 2000 -- and if you think the Perl code is bad, you should see those HTML files!

I've written some worse stuff too, purposely thinking about entering the obfuscated perl code contest, but out of my real code for real purposes, the above is about the worst.

And no, I wasn't fired for that! :)

I would also like to point out that the ugliness of my code is not a property of it being Perl, but rather that I'm using ugly regular expressions. Regular expressions tend to be almost a language in and of themselves, and can be used in many languages, like C (with PCRE) and PHP.

</rant>

-- Ezran
 
I am rather fond of this snippet, from only a couple weeks ago:
code:<HR>
Code:
	if( (	BoxStart.y	>= ScreenStart.y && BoxStart.y	<= ScreenEnd.y		&&
			BoxStart.x	>= ScreenStart.x && BoxStart.x	<= ScreenEnd.y )	||
		(	BoxStart.y	>= ScreenStart.y && BoxStart.y	<= ScreenEnd.y		&&
			BoxEnd.x	>= ScreenStart.x && BoxEnd.x	<= ScreenEnd.x )	||
		(	BoxEnd.y	>= ScreenStart.y && BoxEnd.y	<= ScreenEnd.y		&&
			BoxStart.x	>= ScreenStart.x && BoxStart.x	<= ScreenEnd.x )	||
		(	BoxEnd.y	>= ScreenStart.y && BoxEnd.y	<= ScreenEnd.y		&&
			BoxEnd.x	>= ScreenStart.x && BoxEnd.x	<= ScreenEnd.x )	)
	{
			return( true );
	}

Hey, at least I bother to format my otherwise unreadable code :)

PO
 

hanser

Ars Legatus Legionis
43,847
Subscriptor++
No really code, but Jesus! The amount of comments our prof requires us to write is fucking unbelievable. More comment than code most of the time. :rolleyes:

Example:

code:<HR>
Code:
/* ********************************************************************************
   Function: NoPlayers
   Returns: true if there are no players in the circular linked list;
            false otherwise.
   Params: pointer to a Players structure.  The pointer MUST point to
   an actual structure and NOT have a NULL value
   Uses: 
   Library Headers: 
   Side Effects: none. 
   Compiler Requirements: g++
 ******************************************************************************** */
bool NoPlayers(Players *ps){
	return (ps->count == 0);
}

/* ********************************************************************************
   Function: MakePlayer
   Returns: a pointer to a newly allocated player structure.
   Params: an integer, used as a unique indentifier for the new structure.
   Uses: malloc
   Library Headers: stdlib.h
   Side Effects: allocates a new player structure and assigns the parameter
   value to the id field of the new structure.
 ******************************************************************************** */
Player* MakePlayer(int new_id){
	Player *p;
	p = (Player *) malloc(sizeof(Player));
	p->id = new_id;

	return p;
}

/* ********************************************************************************
   Function: AddPlayer
   Returns: 
   Params: a non-NULL pointer to a player structure; a pointer to the header of
   a circular list of players.
   Uses: 
   Library Headers:
   Side Effects: inserts the single player structure into the circular list,
   at the location just beyond that pointed to by the 'current' field.
 ******************************************************************************** */
void AddPlayer(Player *p, Players *ps){
	 if(ps->count == 0){
		 p->Link = p;
		 ps->current = p;
		 ps->count++ ;
	 }
	 else{
		 p->Link = ps->current->Link;
		 ps->previous = ps->current;
		 ps->current->Link = p;
		 ps->current = p;
		 ps->count++ ;
	 }
}


/* ********************************************************************************
   Function: NumberOfPlayers
   Returns: an integer - the number of elements in the circular list, as given
   by the count field of the header.
   Params: a pointer to the header of a circular list of players.
   Uses: 
   Library Headers:
   Side Effects: none.
 ******************************************************************************** */
int NumberOfPlayers(Players *ps){
	return ps->count;
}
etc.


ugh. It's impossible to work with. That many comments is just too cumbersome to be effective.
 
I don't have a copy of the code but I think it was something like:

dosomething( $myarray[3][$i * $j + $k][$myarray[1][$j]][$k] )

Did you catch that? The third subscript to my four dimensional array was the same array accessed as a two dimensional array. Depending on the first subscript the array was either 2, 3, or 4 dimensions. It made sense at the time...
 

Sheriff

Ars Tribunus Militum
1,841
here we go, a nav bar used in one section of our site: relys on a bunch of global variables and crap. If we didnt already have to many things on our plate we'd rewrite it, but it is low on the list.

code:<HR>
Code:
 sub PageNavBarExternal()
		
		If Request.QueryString("WhichPageExternal") <> "" then
			pageExternal = Request.QueryString("WhichPageExternal")
			
		else
			pageExternal = 1
		end if
		
		rs.AbsolutePage = pageExternal
		maxpages = rs.PageCount
		
		
		
		pad=""
		scriptname=request.servervariables("script_name")
		pageText="<table cellpadding=""3"" cellspacing=""3"" border=""0""><tr>"
		pageText=PageText& "<td bgcolor=""#ffcc66"">"
		pageText=PageText& "Page " & pageExternal & " of " & maxpages & " "
      
      if (pageExternal mod 10) = 0 then
       counterstart = pageExternal - 9
      else
       counterstart = pageExternal - (pageExternal mod 10) + 1
      end if
      counterend = counterstart + 9
      if counterend > maxpages then counterend = maxpages
      if counterstart <> 1 then
       ref="<a href=""" & scriptname
       ref=ref & "?whichpage" & scope & "=" & 1
       ref=ref & "&WhichPageInternal=" & Request.QueryString("WhichPageInternal")
      
       ref=ref & """>First</a> : "
       pageText=PageText& ref


       ref="<a href=""" & scriptname
       ref=ref & "?whichpage" & scope & "=" & (counterstart - 1)
       ref=ref & "&WhichPageInternal=" & Request.QueryString("WhichPageInternal")
     
       ref=ref & """>Previous</a> "
      pageText=PageText& ref
      end if
     pageText=PageText& "[ "
    
      for counter=counterstart to counterend
       If counter>=10 then
			pad=""
       end if
       if cstr(counter) <> pageExternal then
			ref="<a href=""" & scriptname
			ref=ref & "?whichpage" & scope & "=" & counter
			ref=ref & "&WhichPageInternal=" & Request.QueryString("WhichPageInternal")
      
			ref=ref & """>" & pad & counter & "</a>"
       else
			ref="<b>" & pad & counter & "</b>"
       end if
		pageText=PageText& ref
       if counter <> counterend then pageText=PageText& " "
        
      next
		pageText=PageText& " ]"
			if counterend <> maxpages then
					ref=" <a href=""" & scriptname
					ref=ref & "?whichpage" & scope & "=" & (counterend + 1)
					ref=ref & "&WhichPageInternal=" & Request.QueryString("WhichPageInternal")
      
					ref=ref & """>Next</a>"
					pageText=PageText& ref


					ref=" : <a href=""" & scriptname
					ref=ref & "?whichpage" & scope & "=" & maxpages
					ref=ref & "&WhichPageInternal=" & Request.QueryString("WhichPageInternal")
					ref=ref & """>Last</a>"
					pageText=PageText&ref
			end if
		pageText=PageText& "
"
		pageText=PageText&"</td>"
		pageText=PageText& "</table>"
		
		OutputText = OutputText & PageText
end sub

note that this is pagenavbarexternal, there is also a pagenavbarinternal which is the exact same code with internal replacing External wherever in the code.
 
here's some good stuff:
code:<HR>
Code:
 template <class T>
Rlist<T>& append (Rlist<T>& l, const T& item) {
	return l.isEmpty()? insert(l, item) : append(l.tail(), item);
}

that was part of a class i had to create to handle recursive lists... i guess the code isn't really all that sick, it's just a sick idea...

----------------
Crackez
 

AlphaMeridian

Ars Legatus Legionis
17,136
Moderator
Oh sweet god Hanser! And I thought my C++ prof was bad.

Not only do we have to line up all of the semicolons and the equals signs, but we have to put all of our variables in alphabetical order, and some stupid naming scheme with if it's a total, it has to have tot in front of it.....just a whole conglomeration of stupid shit.

But Hanser....your prof takes the cake. I mean, sweet god, You can include all the pertentant information in a simple:

//precondition
//postcondition

lines. I mean "uses: malloc"?!?!?!? "library headers: stdlib.h"

Sweet jesus. Tell him that I said to smack him upside the head with a clueX4 and instead of:
code:<HR>
Code:
/* ********************************************************************************   
Function: MakePlayer
Returns: a pointer to a newly allocated player structure. 
Params: an integer, used as a unique indentifier for the new structure.  
Uses: malloc  
Library Headers: stdlib.h 
Side Effects: allocates a new player structure and assigns the parameter  
 value to the id field of the new structure. 
******************************************************************************** */

use:

code:<HR>
Code:
//precondition: An Integer used for unique naming purposes
//postcondition: Returns a pointer to a newly created, unique structure

But i expect that is too much common sense for him to handle.

-Alpha

EDIT: One small question.

is:

p = (Player *) malloc(sizeof(Player)); Equivalent to: p = new Player;

I'm trying to bone up on linked list/linked lists syntax in C++.
 

Clintology

Ars Legatus Legionis
15,566
Subscriptor
I think CUPL in general is ugly

code:<HR>
Code:
NAME	MOTOR; /* 8 Characters Max */
PARTNO		;
REVISION	;
DATE	02/14/2002		;
DESIGNER	Clint Ecker;
COMPANY		;
LOCATION	;
DEVICE		G16V8A;


/*

Design a stepper motor sequence controller

CW:
0101->0001->1001->1000->1010->0010->0110->0100.
 ^____________________________________________|

CCW:
0101->0100->0110->0010->1010->1000->1001->0001.
^_____________________________________________|

STEP	CW	function
----    --      --------
0	X	HALT
1	0	CCW
1	1	CW

*/

pin 1 = CLK;		/* Counter Clock Input */
pin 2 = STEP;		/* STEP control */
pin 3 = CLW;		/* Direction control */
pin 11 = !oe;		/* Register output enable */


/* Outputs */

pin [12..15] = [Q0..Q3];

/* Definitions */

field counter = [Q3..0];	/* Counter bit field */
field mode = [STEP, CLW];	/* Mode bit field */
HOLD = STEP:[0,1];
CCW = mode:2;
CW = mode:3;

$define S0 'b'0101
$define S1 'b'0001
$define S2 'b'1001
$define S3 'b'1000
$define S4 'b'1010
$define S5 'b'0010
$define S6 'b'0110
$define S7 'b'0100

$define S8 'b'0000
$define S9 'b'0011
$define S10 'b'0111
$define S11 'b'1011
$define S12 'b'1100
$define S13 'b'1101
$define S14 'b'1110
$define S15 'b'1111

/* Logic Equations */

sequence counter {
	
	/* States Not Used */
	
	present S8	if HOLD		next S8;
			default		next S0;
	
	present S9	if HOLD		next S9;
			default		next S0;
	
	present S10	if HOLD		next S10;
			default		next S0;
	
	present S11	if HOLD		next S11;
			default		next S0;
	
	present S12	if HOLD		next S12;
			default		next S0;
	
	present S13	if HOLD		next S13;
			default		next S0;
	
	present S14	if HOLD		next S14;
			default		next S0;
	
	present S15	if HOLD		next S15;
			default		next S0;

	
	/* Real States */
	
	present S0	if HOLD		next S0;
			if CW		next S1;
			if CCW		next S7;

	present S1	if HOLD		next S1;
			if CW		next S2;
			if CCW		next S0;

	present S2	if HOLD		next S2;
			if CW		next S3;
			if CCW		next S1;
	
	present S3	if HOLD		next S3;
			if CW		next S4;
			if CCW		next S2;
	
	present S4	if HOLD		next S4;
			if CW		next S5;
			if CCW		next S3;
	
	present S5	if HOLD		next S5;
			if CW		next S6;
			if CCW		next S4;
	
	present S6	if HOLD		next S6;
			if CW		next S7;
			if CCW		next S5;
		
	present S7	if HOLD		next S7;
			if CW		next S0;
			if CCW		next S6;
}

=clint
 
euzeka, here's the class it self:
rlist.hpp:
code:<HR>
Code:
#ifndef RLIST_HPP
#define RLIST_HPP

template <class T> class Rnode;
template <class T>
class Rlist {
	public :
		Rlist ();                            // Empty list
		Rlist (T, Rlist<T> const&);          // One item plus copy
		Rlist (Rlist<T> const&);
		~Rlist ();
		Rlist<T>& operator= (Rlist<T> const&);
		Rlist<T>& swap (Rlist<T>&);          // Exchange *this/parm
		int isEmpty () const;
		T const& head () const;              // The first item
		T& head ();            
		Rlist<T> const& tail () const;       // All but the first item
		Rlist<T>& tail ();            
	private :
		Rnode<T>* data;
	};

#include "rlist.cpp"
#endif

rlist.cpp:
code:<HR>
Code:
template <class T>
class Rnode {
	friend class Rlist<T>;
	private :
		Rnode (T v, Rlist<T> const& l) : next(l), data(v) { }
		Rlist<T> next;
		T data;
	};
int Rlist_count(0), Rlist_calls(0);
template <class T>
Rlist<T>::Rlist () : data(0) {
	++ Rlist_calls;
	++ Rlist_count;
	}
template <class T>
Rlist<T>::Rlist (T v, Rlist<T> const& l) : data(new Rnode<T>(v, l)) {
	++ Rlist_calls;
	++ Rlist_count;
	}
template <class T>
Rlist<T>::Rlist (Rlist<T> const& s)
		: data(s.data ? new Rnode<T>(*s.data) : 0) {
	++ Rlist_calls;
	++ Rlist_count;
	}
template <class T>
Rlist<T>::~Rlist () {
	++ Rlist_calls;
	delete data;
	if (-- Rlist_count == 0)
		cerr << Rlist_calls << " Rlist member calls.\n";
	}
template <class T>
Rlist<T>& Rlist<T>::swap (Rlist<T>& other) {
	++ Rlist_calls;
	Rnode<T>* tmp(data);
	data = other.data;
	other.data = tmp;
	return *this;
	}
template <class T>
Rlist<T>& Rlist<T>::operator= (Rlist<T> const& rhs) {
	Rlist<T> tmp(rhs);
	return swap(tmp);
	}
template <class T>
int  Rlist<T>::isEmpty () const {
	++ Rlist_calls;
	return data == 0;
	}
template <class T>
T const& Rlist<T>::head () const {
	++ Rlist_calls;
	return data->data;
	}
template <class T>
T& Rlist<T>::head () {
	return const_cast<T&>(static_cast<Rlist const*>(this)->head());
	}
template <class T>
Rlist<T> const& Rlist<T>::tail () const {
	++ Rlist_calls;
	return data->next;
	}
template <class T>
Rlist<T>& Rlist<T>::tail () {
	return const_cast<Rlist&>(static_cast<Rlist const*>(this)->tail());
	}

That part is written by John Potter, my professor for that class.
here's my part:
code:<HR>
Code:
#include "rlist.hpp"
#include <iostream>

template <class T> Rlist<T>& insert (Rlist<T>&, const T&);
template <class T> int size (const Rlist<T>&);
template <class T> ostream& operator<< (ostream&, const Rlist<T>&);
template <class T> Rlist<T>& append (Rlist<T>&, const T&);
template <class T, class IS> IS& operator>> (IS&, Rlist<T>&);
template <class T> Rlist<T> reverse (const Rlist<T>&);

// Adds an item to the front of a list and returns the list #1
template <class T>
Rlist<T>& insert (Rlist<T>& l, const T& item) {
	return l=Rlist<T>(item, l);
}

// returns the number of items on the list #2
template <class T> int size (const Rlist<T>& l) {
	return l.isEmpty()? 0 : size(l.tail())+1;
}

// Prints a list on a stream #3
template <class T>
ostream& operator<< (ostream& os, const Rlist<T>& l) {
	return l.isEmpty()? os << "" : os << l.head() << l.tail();
}

// Adds an item to the end of a list and returns the list #4
template <class T>
Rlist<T>& append (Rlist<T>& l, const T& item) {
	return l.isEmpty()? insert(l, item) : append(l.tail(), item);
}

// Reads a list from a stream through EOF #5
template <class T, class IS>
IS& operator>> (IS& is, Rlist<T>& l) {
	T item;
	l=Rlist<T>();
	while(is >> item)
		append(l, item);
	return is;	
}

// Returns a list which is the reverse of the given list #6
template <class T>
Rlist<T> reverse (Rlist<T> const& l) {
	
	if(!l.isEmpty()){
		ret=reverse(l.tail());
		ret=append(ret, l.head());
	} else 
		ret=l;
		
	return ret;
}


int main () {
	{
		Rlist<int> l(69, Rlist<int>(42, Rlist<int>()));
		cout << "My list of two items has size = " << size(l) << endl;
		cout << "Inserting an item\n";
		insert(l, 8);
		cout << "l(" << size(l) << ") = " << l << endl;
		cout << "Appending an item\n";
		append(l, 8); 
		cout << "l(" << size(l) << ") = " << l << endl; 
		}
	Rlist<int> l;
	cout << "Let's build a list of int using the input operator" << endl;
	cout << "Enter some ints ending with ^D on a line alone" << endl;
	cin >> l;
	cin.clear();
	cout << "l(" << size(l) << ") = " << l << endl;
	cout << "Now add one more to the front of it" << endl;
	int x;
	cin >> x;
	cout << "l = " << insert(l, x) << endl;
	cout << "l(" << size(l) << ") = " << l << endl;
	cout << "And add one more to the end of it" << endl;
	cin >> x;
	cout << "l = " << append(l, x) << endl;
	cout << "l(" << size(l) << ") = " << l << endl;
	cout << "Now a reversal" << endl;
	Rlist<int> r(reverse(l));
	cout << "r(" << size(r) << ") = " << r << endl;
	cout << "l(" << size(l) << ") = " << l << endl;
	cout << "How about reading a new list with the input operator" << endl;
	cout << "Enter some ints ending with ^D on a line alone" << endl;
	cin >> l;
	cin.clear();
	cout << "l(" << size(l) << ") = " << l << endl; 
}

--------------
Crackez
 

Tychom

Ars Tribunus Militum
2,391
Subscriptor
i just remembered this i wrote, it isnt finished and is a very long set of macros (4 of them making up ~250 lines) so i'll just post bits of it

code:<HR>
Code:
#define nt_define(_VALTYPE)																						 \
typedef struct _nt ## _VALTYPE nt ## _VALTYPE, * pnt ## _VALTYPE;										 \
pnt ## _VALTYPE nt ## _VALTYPE ## _new();																	 \
pnt ## _VALTYPE nt ## _VALTYPE ## _incr(pnt ## _VALTYPE * n);										 \
pnt ## _VALTYPE nt ## _VALTYPE ## _decr(pnt ## _VALTYPE * n);										 \
_VALTYPE nt ## _VALTYPE ## _get_val(pnt ## _VALTYPE n);													 \
void nt ## _VALTYPE ## _set_val(pnt ## _VALTYPE n, _VALTYPE val);											 \
...
typedef struct _nt ## _VALTYPE																 \
{																									 \
	struct _nt ## _VALTYPE * fwrd;															 \
	struct _nt ## _VALTYPE * back;															 \
	_VALTYPE val;																					 \
} nt ## _VALTYPE, * pnt ## _VALTYPE;													 \
...
void nt ## _VALTYPE ## _foreach(pnt ## _VALTYPE start,pnt ## _VALTYPE finish,void (*f)(_VALTYPE *)) \
{																									 \
	pnt ## _VALTYPE i = start;																 \
	_VALTYPE tmp;																					 \
	for (; i != finish; nt ## _VALTYPE ## _incr(&i))										 \
	{																								 \
		tmp = nt ## _VALTYPE ## _get_val(i);												 \
		f(&tmp);																					 \
	}																								 \
}																									 \
void nt ## _VALTYPE ## _insert_before(pnt ## _VALTYPE n,_VALTYPE val)					 \
{																									 \
	pnt ## _VALTYPE new_node;																	 \
	new_node = nt ## _VALTYPE ## _new();													 \
	new_node->val = val;																			 \
	new_node->fwrd = n;																				 \
	new_node->back = n->back;																		 \
	new_node->fwrd->back = new_node;																 \
	new_node->back->fwrd = new_node;																 \
}																									 \
void nt ## _VALTYPE ## _insert_after(pnt ## _VALTYPE n,_VALTYPE val)					 \
{																									 \
	nt ## _VALTYPE ## _insert_before(n->fwrd,val);											 \
}																									 \
...
#define lt_define(_VALTYPE)																	 \
typedef struct _lt ## _VALTYPE lt ## _VALTYPE, * plt ## _VALTYPE;					 \
plt ## _VALTYPE  lt ## _VALTYPE ## _new();											 \
void lt ## _VALTYPE ## _delete(plt ## _VALTYPE l);									 \
long lt ## _VALTYPE ## _length(plt ## _VALTYPE l);									 \
pnt ## _VALTYPE lt ## _VALTYPE ## _begin(plt ## _VALTYPE l);					 \
pnt ## _VALTYPE lt ## _VALTYPE ## _end(plt ## _VALTYPE l);						 \
...
void lt ## _VALTYPE ## _push_front(plt ## _VALTYPE l,_VALTYPE val)					 \
{																									 \
	nt ## _VALTYPE ## _insert_before(nt ## _VALTYPE ## _incr(&(l->head)),val);		 \
	l->length += 1;																					 \
}																									 \
void lt ## _VALTYPE ## _pop_front(plt ## _VALTYPE l)									 \
{																									 \
	nt ## _VALTYPE ## _remove(l->head);														 \
	l->length -= 1;																					 \
}																									 \
pnt ## _VALTYPE lt ## _VALTYPE ## _find(plt ## _VALTYPE l,_VALTYPE val)			 \
{																									 \
	pnt ## _VALTYPE i;																		 \
	for (i = lt ## _VALTYPE ## _begin(l); i != lt ## _VALTYPE ## _end(l); nt ## _VALTYPE ## _incr(&i)) \
	{																								 \
		if (nt ## _VALTYPE ## _get_val(i) == val) return i;									 \
	}																								 \
	return i;																						 \
}																									 \
...

its wonderful to debug :eek: :eek: :(
 

iceburn

Wise, Aged Ars Veteran
195
Subscriptor
Hanser - Man, that brings back bad memories. My C++ prof made us do almost exactly the same thing. But we had to document everything in the code as well. In a linked-list class, just having pointers named prev, next, curr, etc wasn't enough, we had to document what they were for! Even had to document 'int i = 0' before a for loop, to say what 'i' did!

Saddest thing - he told us that when we got out into the 'real world' we would have to write an average of 4 lines of doc for every 1 line of code at most places. He said he was being easy on us. I later found out he's never worked anywhere outside of the school. Poor bastard.
 

pelican

Wise, Aged Ars Veteran
184
_klamath_:

Merriam Webster's definition of "nihilism":

1 a : a viewpoint that traditional values and beliefs are unfounded and that existence is senseless and useless b : a doctrine that denies any objective ground of truth and especially of moral truths


Don't you ever look at something you wrote, and go, what in the fuck was I thinking when I wrote that?

--pelican

EDIT: Love those comments man! I'd have 850 line objects for sure, with that type of commenting -- ;) --

p.s.
code:<hr>
Code:
 echo "<img border=\"0\"src=\"image.php?image=$imagepath&map_zoom_x=$map_zoom_x&map_zoom_y=$map_zoom_y&height=$this->height&width=$this->width\">"; }
 

newton_meter

Ars Scholae Palatinae
1,424
CL's prog, as a Scheme macro. I had to use a hygeine "feature". I did it for an assignment, I don't really use prog.

code:<HR>
Code:
(define-syntax prog
  (syntax-rules ()
    ((_ (Goto Return))
     (prog (Goto Return) start))

    ((_ (Goto Return) (Stmt ...) Rest ...)
     (prog (Goto Return) start (Stmt ...) Rest ...))

    ((_ (Goto Return) Label Rest ...)
     (prog "label" (Goto Return) Label () () Label Rest ... (Return (void))))

    ((_ "label" (Goto Return) Label (Stmts ...) (Decls ...) Body (Stmt ...)
       Rest ...)
     (prog "label" (Goto Return) Label (Stmts ... (Stmt ...)) (Decls ...)
       Body Rest ...))

    ((_ "label" (Goto Return) Label (Stmts ...) (Decls ...) Body
       NewLabel Rest ...)
     (prog "label" (Goto Return) NewLabel ()
       (Decls ... (Label (lambda () Stmts ... (Goto NewLabel))))
       Body Rest ...))

    ((_ "label" (Goto Return) Label (Stmts ...) (Decls ...) Body)
     ((call/cc
	(lambda (Goto)
	  (let-syntax ((Return (syntax-rules ()
				 ((_ Exp) (Goto (lambda () Exp))))))
	    (letrec (Decls ... (Label (lambda () Stmts ...)))
	      Body))))))))

(kg*m*m)/(s*s)
 

Tristram

Ars Scholae Palatinae
1,428
Subscriptor
p = (Player *) malloc(sizeof(Player)); Equivalent to: p = new Player;

I'm trying to bone up on linked list/linked lists syntax in C++.

Unless Player is a typedef for a built in type (int, float, etc.), or a simple struct, probably not. The C++ operator new() will not only reserve space (ala malloc()), but will also invoke the default constructor to initialize the memory. If there are no constructors defined, the C++ compiler will appoint one for you (and like public defenders, you get what you pay for ;)). If you do have constuctors defined, but no default (i.e, takes no arguments, or has defaults for all arguments), this will be an error.
 
I just thought of another one i had lying around.... this was done to demostrate and idea though...

code:<HR>
Code:
// ReverseList Function

struct Node { Node(int d, Node* n) : data(d), next(n); int data; Node* next; };

Node* ReverseList (Node* head) {
	Node* node;
	Node* new_node;
	for(node = new Node(head ->data, NULL); head ->next != NULL; node = new_node){
		head = head ->next;
		new_node = new Node(head ->data, node);
	}
	return node;
}
 
Here, i've got another one:
code:<HR>
Code:
       IDENTIFICATION DIVISION.
       PROGRAM-ID. 32003.
       AUTHOR. Andy Stanton.
       INSTALLATION. LOCK HAVEN UNIVERSITY.
      ************************************
      *               32003              *
      * THIS PROGRAM GENERATES A MONTHLY *
      * CREDIT CARD ACTIVITY REPORT FROM *
      * A CUSTOMER ACCOUNT INFORMATION   *
      * FILE FOR THE COMP320 CREDIT CARD *
      * SYSTEM. (C) ANDY STANTON, 2002.  *
      ************************************      
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       SOURCE-COMPUTER. AMD-K6-2-x86.
       OBJECT-COMPUTER. IBM-RISC-6000.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
         SELECT I-MAST-FILE
           ASSIGN "/home1/apotter/data/32003"
           ORGANIZATION IS LINE SEQUENTIAL.
         SELECT O-REPORT-FILE
           ASSIGN "32003.out"
           ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD I-MAST-FILE
         RECORD CONTAINS 80 CHARACTERS.
       01 I-CUST-REC.
           05 I-ACCT-NUM.
               10 I-REG-NUM         PIC 99.
               10 I-BRANCH-NUM      PIC 999.
               10 I-CARD-NUM        PIC 9(5).
               10 I-ACCT-SUF        PIC A.
           05 I-CUST-NAME.
               10 I-LAST            PIC X(10).
               10 I-FIRST           PIC X(10).
           05                       PIC X(9).
           05 I-MONTH-ACT.
               10 I-CHARGES         PIC 9(5)V99.
               10 I-PAYMENTS        PIC 9(5)V99.
           05 I-CARD-INFO.
               10 I-INTEREST-RATE    PIC V99.
               10 I-CUR-BAL         PIC 9(5)V99.
               10 I-ISS-DATE.
                   15 I-ISS-MON     PIC 99.
                   15 I-ISS-YR      PIC 9999.
               10 I-EXP-DATE.
                   15 I-EXP-MON     PIC 99.
                   15 I-EXP-YR      PIC 9999.
               10 I-CRED-LIMIT      PIC 9(5).
       FD O-REPORT-FILE
         RECORD CONTAINS 80 CHARACTERS.
       01 O-REPORT-REC              PIC X(80).
       WORKING-STORAGE SECTION.
       01 WS-HEADING.
           05 WS-LINE-ONE.
               10                   PIC X(25) VALUE SPACES.
               10                   PIC X(31) 
                   VALUE 'MONTHLY CREDIT ACTIVITY LISTING'.
               10                   PIC X(15) VALUE SPACES.
               10                   PIC X(5) VALUE 'PAGE '.
               10 WS-PAGE-COUNT-O   PIC Z9.
               10                   PIC XX VALUE SPACES.
           05 WS-BLANK-LINE         PIC X(80) VALUE SPACES.
           05 WS-LINE-TWO.
               10                   PIC X(16) VALUE SPACES.
               10                   PIC X(9) VALUE 'BEGINNING'.
               10                   PIC X(34) VALUE SPACES.
               10                   PIC X(6) VALUE 'ENDING'.
               10                   PIC X(4) VALUE SPACES.
               10                   PIC X(9) VALUE 'AVAILABLE'.
               10                   PIC XX VALUE SPACES.
           05 WS-LINE-THREE.
               10                   PIC X(6) VALUE SPACES.
               10                   PIC X(4) VALUE 'NAME'.
               10                   PIC X(7) VALUE SPACES.
               10                   PIC X(7) VALUE 'BALANCE'.
               10                   PIC X(3) VALUE SPACES.
               10                   PIC X(8) VALUE 'PAYMENTS'.
               10                   PIC XX VALUE SPACES.
               10                   PIC X(8) VALUE 'INTEREST'.
               10                   PIC XXX VALUE SPACES.
               10                   PIC X(7) VALUE 'CHARGES'.
               10                   PIC X(4) VALUE SPACES.
               10                   PIC X(7) VALUE 'BALANCE'.
               10                   PIC XX VALUE SPACES.
               10                   PIC X(10) VALUE 'CREDIT LIM'.
               10                   PIC XX VALUE SPACES.
       01 WS-DETAIL-LINE.
           05 WS-NAME.
               10                   PIC XX VALUE SPACES.
               10 WS-F-INIT         PIC X.
               10                   PIC X VALUE SPACE.
               10 WS-LAST           PIC X(10).
               10                   PIC X VALUE SPACE.
           05 WS-BEG-BAL-O          PIC $$$,$$9.99.
           05                       PIC XX VALUE SPACES.
           05 WS-PAYMENTS-O         PIC ZZ,ZZ9.99.
           05                       PIC X VALUE SPACE.
           05 WS-INTEREST-O         PIC Z,ZZ9.99.
           05                       PIC XX VALUE SPACES.
           05 WS-CHARGES-O          PIC ZZ,ZZ9.99.
           05                       PIC X VALUE SPACE.
           05 WS-END-BAL-O          PIC $$$,$$9.99.
           05                       PIC X VALUE SPACE.
           05 WS-AVAIL-CRED-O       PIC $$$,$$9.99.
           05                       PIC XX VALUE SPACES.
       01 WS-TOTAL-LINE.
           05                       PIC XX VALUE SPACES.
           05                       PIC X(6) VALUE 'TOTALS'.
           05                       PIC X(7) VALUE SPACES.
           05 WS-TOT-BEG-BAL-O      PIC $$$,$$9.99.
           05                       PIC XX VALUE SPACES.
           05 WS-TOT-PAYMENTS-O     PIC ZZ,ZZ9.99.
           05                       PIC X VALUE SPACE.
           05 WS-TOT-INTEREST-O     PIC Z,ZZ9.99.
           05                       PIC XX VALUE SPACES.
           05 WS-TOT-CHARGES-O      PIC ZZ,ZZ9.99.
           05                       PIC X VALUE SPACE.
           05 WS-TOT-END-BAL-O      PIC $$$,$$9.99.
           05                       PIC X VALUE SPACE.
           05 WS-TOT-AVAIL-CRED-O   PIC $$$,$$9.99.
           05                       PIC XX VALUE SPACES.
       01 WS-CUST-AMTS.
           05 WS-BEG-BAL            PIC 9(5)V99.
           05 WS-PAYMENTS           PIC 9(5)V99.
           05 WS-INTEREST           PIC 9(4)V99.
           05 WS-INTEREST-RATE      PIC V9999.
           05 WS-CHARGES            PIC 9(5)V99.
           05 WS-END-BAL            PIC 9(5)V99.
           05 WS-AVAIL-CRED         PIC 9(5)V99.
       01 WS-TOTALS.
           05 WS-TOT-BEG-BAL        PIC 9(5)V99 VALUE ZEROES.
           05 WS-TOT-PAYMENTS       PIC 9(5)V99 VALUE ZEROES.
           05 WS-TOT-INTEREST       PIC 9(4)V99 VALUE ZEROES.
           05 WS-TOT-CHARGES        PIC 9(5)V99 VALUE ZEROES.
           05 WS-TOT-END-BAL        PIC 9(5)V99 VALUE ZEROES.
           05 WS-TOT-AVAIL-CRED     PIC 9(5)V99 VALUE ZEROES. 
       01 WS-TEMP-VAR               PIC 9(5)V9999 VALUE ZEROES.
       01 WS-MORE-DATA              PIC X VALUE 'N'.
           88 NO-MORE-DATA VALUE 'Y'.
       01 PAGING-CONTROLS.
           05 WS-LINE-COUNT         PIC 99 VALUE 15.
           05 WS-PAGE-COUNT         PIC 99 VALUE ZEROES.
       PROCEDURE DIVISION.
       A0100-MAIN.
           PERFORM B0100-INITIALIZE
           PERFORM B0200-PROCESS-RECORDS
               UNTIL NO-MORE-DATA
           PERFORM B0300-WRAPUP
           STOP RUN.
       B0100-INITIALIZE.
           OPEN INPUT I-MAST-FILE
                OUTPUT O-REPORT-FILE.
       B0200-PROCESS-RECORDS.
           READ I-MAST-FILE
               AT END PERFORM C0300-TOTALS
               NOT AT END PERFORM C0100-WRITE-REC.
       B0300-WRAPUP.
           CLOSE I-MAST-FILE
                 O-REPORT-FILE.
       C0100-WRITE-REC.
           IF WS-LINE-COUNT > 14
               PERFORM C0200-WRITE-HEADING
           END-IF 
           PERFORM D0100-GENERATE-DETAIL-LINE.
       C0200-WRITE-HEADING.
           ADD 1 TO WS-PAGE-COUNT
           MOVE WS-PAGE-COUNT TO WS-PAGE-COUNT-O
           WRITE O-REPORT-REC FROM WS-LINE-ONE
           WRITE O-REPORT-REC FROM WS-BLANK-LINE
           WRITE O-REPORT-REC FROM WS-LINE-TWO
           WRITE O-REPORT-REC FROM WS-LINE-THREE
           WRITE O-REPORT-REC FROM WS-BLANK-LINE
           MOVE 5 TO WS-LINE-COUNT.
       C0300-TOTALS.
           MOVE 'Y' TO WS-MORE-DATA
           MOVE WS-TOT-BEG-BAL TO WS-TOT-BEG-BAL-O
           MOVE WS-TOT-PAYMENTS TO WS-TOT-PAYMENTS-O
           MOVE WS-TOT-INTEREST TO WS-TOT-INTEREST-O
           MOVE WS-TOT-CHARGES TO WS-TOT-CHARGES-O
           MOVE WS-TOT-END-BAL TO WS-TOT-END-BAL-O
           MOVE WS-TOT-AVAIL-CRED TO WS-TOT-AVAIL-CRED-O
           WRITE O-REPORT-REC FROM WS-BLANK-LINE
           WRITE O-REPORT-REC FROM WS-TOTAL-LINE.
       D0100-GENERATE-DETAIL-LINE.
           MOVE I-FIRST TO WS-F-INIT
           MOVE I-LAST TO WS-LAST
           MOVE I-CUR-BAL TO WS-BEG-BAL
           MOVE I-CUR-BAL TO WS-BEG-BAL-O
           ADD WS-BEG-BAL TO WS-TOT-BEG-BAL
           MOVE I-PAYMENTS TO WS-PAYMENTS
           MOVE I-PAYMENTS TO WS-PAYMENTS-O
           ADD WS-PAYMENTS TO WS-TOT-PAYMENTS
           MOVE I-CHARGES TO WS-CHARGES
           MOVE I-CHARGES TO WS-CHARGES-O
           ADD WS-CHARGES TO WS-TOT-CHARGES
           SUBTRACT WS-PAYMENTS FROM WS-BEG-BAL GIVING WS-TEMP-VAR
           DIVIDE I-INTEREST-RATE BY 12 
                GIVING WS-INTEREST-RATE ROUNDED
           MULTIPLY WS-TEMP-VAR BY WS-INTEREST-RATE 
                GIVING WS-INTEREST ROUNDED
           MOVE WS-INTEREST TO WS-INTEREST-O
           ADD WS-INTEREST TO WS-TOT-INTEREST
           SUBTRACT WS-PAYMENTS FROM WS-BEG-BAL GIVING WS-TEMP-VAR
           ADD WS-TEMP-VAR WS-INTEREST TO WS-CHARGES GIVING WS-END-BAL
           MOVE WS-END-BAL TO WS-END-BAL-O
           ADD WS-END-BAL TO WS-TOT-END-BAL
           SUBTRACT WS-END-BAL FROM I-CRED-LIMIT GIVING WS-AVAIL-CRED
           MOVE WS-AVAIL-CRED TO WS-AVAIL-CRED-O
           ADD WS-AVAIL-CRED TO WS-TOT-AVAIL-CRED
           WRITE O-REPORT-REC FROM WS-DETAIL-LINE
           ADD 1 TO WS-LINE-COUNT.

Hows that for lack of morals?
 
From the core of a 2-d maze generator written in C ...
code:<HR>
Code:
for (d=f=l=-1,y=0;y<my;y++) {
    putchar('|');
    for (p=x=0;x<mx;x++) {
        y&&L[x]&2&&(l<0&&(l=M[d]),F[d]<0||(f=F[d]),p+=G[d--]-1);
        p+=y&&L[x]&1;
        R=(x==mx-1||p&&L[x+1]&2);
        (D=(y==my-1||(!R||f>=0)&&r()))||(l=x,f<0&&(f=x));
        C[x]=3*!D;
        R|=(f>=0&&r());
        R&&(p?(F[++d]=f,M[d]=l,G[d]=p,p=0):f>=0&&(C[f]&=1,C[l]&=2),f=l=-1);

        printf(" .\0_.\0 |\0_|\0"+3*D+6*R);
    }
    puts("");
    (t=L,L=C,C=t);
}

No, I can't remember how it works.
 
Status
Not open for further replies.