Coding: Hacks and Snippets

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Coding: Hacks and Snippets

Postby 0xBADFEED » Sat Nov 21, 2009 1:13 am UTC

The other day I wrote a hack and I'm not sure whether to be proud or ashamed.

So I have to use this file-format parser that was written by people that really shouldn't have been writing parsers. It parses a special file-format and is really the only (free) C++ library available that does it. It runs rather slowly so I profiled the code to see what was up. It uses character-at-a-time I/O from a std::istream, so there are lots of get() and putback() calls, thus dedicating a large chunk of the parsing time to locking/unlocking the stream. The parser only operates on a single thread so these locking/unlocking steps are useless. I couldn't recompile the library with a single-threaded runtime as it would screw up other library dependencies.

Rewriting the parsing library was completely unfeasible and the locking behavior is hard-wired into std::basic_istream, so what am I to do? Here's my workaround:

Code: Select all

namespace impl {
    //Create a dummy-type to identify a unique stream type that I can match
    //on for specialization
    template<typename Traits>
    struct _NonLocking : public Traits {};
    //Convenience typedef
    typedef _NonLocking<std::char_traits<char>> _NonLockingCharTraits;
}
/**************************************************************
Create a specialization of the sentry object that controls
the locking behavior of the stream. This injects a new
implementation of the sentry into the std::basic_istream
type when used with _NonLockingCharTraits.
**************************************************************/
template<>
class std::basic_istream<char, ::impl::_NonLockingCharTraits>::_Sentry_base
{
public:
    //required stream type
    typedef std::basic_istream<char,::impl::_NonLockingCharTraits> _Myt;
    //no-op constructor
    _Sentry_base(_Myt& _Istr) :
        _Myistr(_Istr)
    {
        //removed locking code
    }      
    //stream member, used by 'sentry' implementation
    _Myt& _Myistr;   
};
//Keep Non-Locking stream/buf definitions from polluting global namespace
namespace impl {
#define NONLOCKING(type) type<char,_NonLockingCharTraits>
   typedef NONLOCKING(std::basic_istream) _NLInStream;
   typedef NONLOCKING(std::basic_streambuf) _NLStreamBuf;
   typedef NONLOCKING(std::basic_filebuf) _NLFileBuf;
   typedef NONLOCKING(std::basic_stringbuf) _NLStrBuf;   
   typedef NONLOCKING(std::basic_istringstream) _NLInStrStream;
   typedef NONLOCKING(std::basic_ifstream) _NLInFileStream;
#undef NONLOCKING
}

So basically it uses template specialization to inject a new implementation of _Sentry_base (with the locking removed) into std::basic_istream when the Traits type matches my _NonLocking<T> traits type.

After that it was just a simple find/replace in the parser library to substitute the non-locking types for the standard types :|. Note, this only works on MSVS implementations of the C++ standard library as it's completely dependent on that implementation. But I got a parsing speedup of about 40% so whatever, I guess. As dirty as it feels it's not bad for a couple hours work.

User avatar
Earlz
Gets Obvious Implications
Posts: 785
Joined: Sat Jun 09, 2007 8:38 am UTC
Location: USA
Contact:

Re: Coding: Hacks and Snippets

Postby Earlz » Sat Nov 21, 2009 4:59 am UTC

@0xBADBEEF

You are truly a mad man! You must be stopped..

That is a sin on the levels of manipulating the internals of a `FILE` struct in C.
My new blag(WIP, so yes it's still ugly..)
DEFIANCE!
Image
This is microtext. Zooming in digitally makes it worse. Get a magnifying glass.. works only on LCD

fazzone
Posts: 186
Joined: Wed Dec 10, 2008 9:38 pm UTC
Location: A boat

Re: Coding: Hacks and Snippets

Postby fazzone » Sat Nov 21, 2009 5:33 am UTC

Extremely clever. Extremely clever in a terrible, terrible way.
*/

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Sat Nov 21, 2009 12:50 pm UTC

Earlz wrote:@0xBADBEEF

You are truly a mad man! You must be stopped..

That is a sin on the levels of manipulating the internals of a `FILE` struct in C.


IIRC, FILE* isn't even guaranteed to be a pointer to a struct. I've seen instances of it being a void*-casted integer corresponding to the UNIX file descriptor of the file.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Earlz
Gets Obvious Implications
Posts: 785
Joined: Sat Jun 09, 2007 8:38 am UTC
Location: USA
Contact:

Re: Coding: Hacks and Snippets

Postby Earlz » Sat Nov 21, 2009 5:01 pm UTC

You, sir, name? wrote:
Earlz wrote:@0xBADBEEF

You are truly a mad man! You must be stopped..

That is a sin on the levels of manipulating the internals of a `FILE` struct in C.


IIRC, FILE* isn't even guaranteed to be a pointer to a struct. I've seen instances of it being a void*-casted integer corresponding to the UNIX file descriptor of the file.


Well see what I mean! lol

And I believe in most libc implementations for windows, it is a struct with 3 fields.
My new blag(WIP, so yes it's still ugly..)
DEFIANCE!
Image
This is microtext. Zooming in digitally makes it worse. Get a magnifying glass.. works only on LCD

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Coding: Hacks and Snippets

Postby 0xBADFEED » Sat Nov 21, 2009 11:55 pm UTC

You, sir, name? wrote:IIRC, FILE* isn't even guaranteed to be a pointer to a struct. I've seen instances of it being a void*-casted integer corresponding to the UNIX file descriptor of the file.

Yeah, it's not required to even be a pointer to anything. It's not clear to me why it's type FILE* rather than just an opaque handle of type FILE. Not that it really matters.

User avatar
'; DROP DATABASE;--
Posts: 3284
Joined: Thu Nov 22, 2007 9:38 am UTC
Location: Midwest Alberta, where it's STILL snowy
Contact:

Re: Coding: Hacks and Snippets

Postby '; DROP DATABASE;-- » Mon Nov 23, 2009 12:11 am UTC

This is likely the worst hack I've ever used.
lua_touserdata() returns me a pointer to an opaque struct. The only thing I know about this struct is somewhere inside is a pointer to a GtkBox, which I need. So how do I get it?

Code: Select all

//HORRIBLE HORRIBLE HACK TODO: FIX THIS AGH
GtkBox *Container;
void **Ptr = (void**)*(void**)lua_touserdata(Lua, Param++);
for(int i=0; i<4; i++)
{
   if(GTK_IS_BOX(Ptr))
   {
      Container = (GtkBox*)Ptr;
      break;
   }
   Ptr = &Ptr[1];
}
Fortunately GTK uses those nice magic values in its structs that enable GTK_IS_BOX() to tell whether an arbitrary pointer points to a GtkBox. So brute-force test every element of the struct to see if it's a GtkBox! x.x

I'm really hoping this will be a temporary fix until someone who's done this before can tell me the proper solution to my problem. >.>
poxic wrote:You suck. And simultaneously rock. I think you've invented a new state of being.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Mon Nov 23, 2009 12:35 am UTC

'; DROP DATABASE;-- wrote:This is likely the worst hack I've ever used.
lua_touserdata() returns me a pointer to an opaque struct. The only thing I know about this struct is somewhere inside is a pointer to a GtkBox, which I need. So how do I get it?

Code: Select all

//HORRIBLE HORRIBLE HACK TODO: FIX THIS AGH
GtkBox *Container;
void **Ptr = (void**)*(void**)lua_touserdata(Lua, Param++);
for(int i=0; i<4; i++)
{
   if(GTK_IS_BOX(Ptr))
   {
      Container = (GtkBox*)Ptr;
      break;
   }
   Ptr = &Ptr[1];
}
Fortunately GTK uses those nice magic values in its structs that enable GTK_IS_BOX() to tell whether an arbitrary pointer points to a GtkBox. So brute-force test every element of the struct to see if it's a GtkBox! x.x

I'm really hoping this will be a temporary fix until someone who's done this before can tell me the proper solution to my problem. >.>


Seems like a sort of russian roulette with the operating system's memory protection routines, what with the possibility that some struct member isn't a valid pointer, or is of non-pointer size and precedes the sought-after pointer.

Though, beyond the sheer ugliness of the hack, there is something odd about your code. You are feeding GTK_IS_BOX a void**, which is really strange. It should see a void*. This makes the pointers consistent, but it doesn't do the same thing your code does.

Code: Select all

GtkBox *container = NULL;
void **ptr = *((void***) lua_touserdata(lua, param++));
for(int i=0; i<4; i++)
{
   if(GTK_IS_BOX(ptr[i]))
   {
      container = (GtkBox*)(ptr[i]);
      break;
   }
}


Though I may be misunderstanding what you are trying to do.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Tue Dec 08, 2009 11:06 pm UTC

Yeah, I'm pretty sure this is bad. It makes the program take a good five to seven seconds to compile, rather than the near instant compile I get otherwise. I don't know why, though. It also gives a weird compile-time error if the ui() function isn't inline.

Code: Select all

inline void ui(int argc, char **argv)
{
   gtk_init (&argc, &argv);
   //widget stuff goes here
}


Code: Select all

#include "ui.cpp"

int main (int argc, char *argv)
{
   ui(*&argc, &argv);

   //etc...

   return 0;
}
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Coding: Hacks and Snippets

Postby jaap » Wed Dec 09, 2009 12:01 am UTC

I've never used gtk, but I am pretty sure what you posted cannot compile as the referencing/dereferencing is all over the place. Shouldn't it be this:

Code: Select all

inline void ui(int *argc, char ***argv)
{
   gtk_init (argc, argv);
   //widget stuff goes here
}

Code: Select all

#include "ui.cpp"
int main (int argc, char **argv)
{
   ui(&argc, &argv);
   //etc...
   return 0;
}

If your main doesn't use argc/argv, then you could lose one layer of indirection and use this:

Code: Select all

inline void ui(int argc, char **argv)
{
   gtk_init (&argc, &argv);
   //widget stuff goes here
}

Code: Select all

#include "ui.cpp"
int main (int argc, char **argv)
{
   ui(argc, argv);
   //etc... - argc/argc not used after this ui call.
   return 0;
}

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Wed Dec 09, 2009 12:07 am UTC

That works just the same. It might allow me to use command line arguments, but I don't really need to since this is going to be a batch renderer for Blender and thus it won't need arguments itself. (It's like an alternative to command line rendering).

Anyway, the performance in compiling might just be because I have two files instead of one or just that there's an inline function that needs to be processed or something. No biggie.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Wed Dec 09, 2009 12:20 am UTC

Don't trust that library functions are actually functions. They may be macros or some other voodoo. So by moving them out of main, you may be upsetting dark and sinister forces.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Wed Dec 09, 2009 12:51 am UTC

Oh... okay.

I also had problems linking. Renaming certain files to *.c instead of *.cpp fixes it and speeds up compiling for some reason. Huh.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Hacks and Snippets

Postby headprogrammingczar » Wed Dec 09, 2009 2:54 pm UTC

It's might be because you are writing C code instead of C++ code, and the overhead of the more featureful compiling algorithm is slowing down your compiles.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Wed Dec 09, 2009 4:07 pm UTC

headprogrammingczar wrote:It's might be because you are writing C code instead of C++ code, and the overhead of the more featureful compiling algorithm is slowing down your compiles.


I am actually using stdio.h and stdlib.h in one of the files. Other than that, nothing in ui.h would be any different in either language.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

GrantSolar
Posts: 48
Joined: Mon Nov 16, 2009 7:19 pm UTC

Re: Coding: Hacks and Snippets

Postby GrantSolar » Wed Dec 09, 2009 8:37 pm UTC

This whole damn thang reminds me of http://www.gamasutra.com/view/feature/4111/dirty_coding_tricks.php
Of course, that's probably been linked before but I don't care. I play by my own rules... and those of whoever hacked the game together.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Thu Dec 10, 2009 1:30 am UTC

Okay, basically I'm working on a render manager for Blender. Its aim is to be similar to FastF12, but open source and more portable.

Here's what a non-hacker would do:

Code: Select all

//com is the command to render the opened Blender project.
//ex: "blender -b project.blend"

if(!system(com))
{
   printf("Error: Blender is not installed.  You can get it at blender.org");
   return;
}


Here's what I did:

Code: Select all

if(!fopen("/usr/bin/blender","r"))
{      
   if(fopen("/usr/bin/apt","r"))
   {
      system("sudo apt-get install blender");
   }
   else if(fopen("/usr/bin/yum"))
   {
      system("yum install blender");
   }
   else
   {
      if (!system("wget http://mirror.cs.umn.edu/blender.org/source/blender-2.49b.tar.gz")) break;
      if (!system("tar xvf blender-2.49b.tar.gz")) break;
      if (!system("cd blender-2.49b")) break;
      if (!system("make")) break;
      system("sudo make install")
   }
   if(!fopen("/usr/bin/blender","r"))
   {
      printf("Error: Blender is not installed.  This is a freaking render manager for Blender.  INSTALL IT.");
      return 1;
   }
}
else
{
   if(!system(com))
   {
      printf("...You might want to check out Blender++.");
   }
}
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
phlip
Restorer of Worlds
Posts: 7572
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Hacks and Snippets

Postby phlip » Thu Dec 10, 2009 1:34 am UTC

Why on earth would you assume any of those are installed in /usr/bin? You should be checking $PATH...

But really... automatically installing stuff, without asking the user first? Yeah, remind me not to run anything you ever write...

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Thu Dec 10, 2009 1:50 am UTC

phlip wrote:Why on earth would you assume any of those are installed in /usr/bin? You should be checking $PATH...

But really... automatically installing stuff, without asking the user first? Yeah, remind me not to run anything you ever write...


It will ask the user first when it prompt for a password, unless it's run as root, which you shouldn't anyway. Also, I doubt anyone who doesn't have Blender or doesn't want Blender will run this.

As for checking $PATH, yeah. I was trying to find out the program locations. So I would just do this, right?

Code: Select all

fopen("$PATH/blender", "r")
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

Random832
Posts: 2525
Joined: Wed Oct 10, 2007 4:38 pm UTC

Re: Coding: Hacks and Snippets

Postby Random832 » Thu Dec 10, 2009 2:12 am UTC

TheChewanater wrote:
phlip wrote:Why on earth would you assume any of those are installed in /usr/bin? You should be checking $PATH...

But really... automatically installing stuff, without asking the user first? Yeah, remind me not to run anything you ever write...


It will ask the user first when it prompt for a password, unless it's run as root, which you shouldn't anyway. Also, I doubt anyone who doesn't have Blender or doesn't want Blender will run this.


And if they have a custom version of blender installed in some other path?

As for checking $PATH, yeah. I was trying to find out the program locations. So I would just do this, right?

Code: Select all

fopen("$PATH/blender", "r")


No, you have to split it yourself and check each possibility. Why am I telling you this? Seriously,, don't do this.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Thu Dec 10, 2009 2:20 am UTC

Random832 wrote:No, you have to split it yourself and check each possibility. Why am I telling you this? Seriously,, don't do this.

You're right, I don't know what I was thinking. "Hmm, how can I make people pissed off at my program".

For laughs, I might have this featured enabled only if the program is compiled with a certain argument. Or maybe if someone complains that they can't compile it I'll send them a precompiled version with this feature. :P
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Thu Dec 10, 2009 2:41 pm UTC

I'm playing with a loader system I've written with JQuery. It basically dynamically loads a HTML page, and then parses the tree for magical hidden elements that are replaced with dynamic functionality. Now, I want the loader to make some changes to the page before the loaded page starts working, and a script on the loaded page to be run before the loader starts parsing, but since all this is asynchronous, all sorts of race conditions occur. So, here's what I did:

The loaded page has, amongst other things something like this:

Code: Select all

   <form id="loader-variables">
      <input type="hidden" id="load-argument" />
      <textarea style="display: none" id="initializer">
$(function() {
   $('#loader-callbacks #loader-finished').click(function() {
      alert('Done!');
   });
   loader.run('#test');
});
      </textarea>
   </form>


Code: Select all

loader.load = function(elem, url, arg) {
   $(elem).load(url, function() {
      $(elem).find('#loader-variables #load-argument');
      var initializer = $(document.createElement('script'));
      initializer.attr('type', 'text/javascript');
      initializer.text($(elem).find('#loader-variables #initializer').val());
      $(elem).append(initializer);
   });
}

loader.run = function(elem) {
   for(var i = 0; i < loader.handlers.length; i++) {
      loader.handlers[i]($(elem));
   }
   $(elem).find('#loader-callbacks #loader-finished').click();
}


Be afraid. Be very afraid.


But, the end result is all sorts of neat. As long as I keep model and controller strictly adherent to a certain protocol, I can implement a form something like this:

Code: Select all

   <form class="controller-form">
      <input type="hidden" class="action" value="reply" />

      <input type="hidden" class="argument" value="#load-argument" />
      <input type="hidden" class="base" value="#reply" />
      <input type="hidden" class="success" value="#form-submitted" />
   </form>

   <form id="loader-callbacks">
      <a id="form-submitted" style="display: none" /> <!--  A handler binds 'click()' on this link, and it fires after the form is sent with a successful return from the controller -->
   </form>

   <div id="reply" style="padding: 1em">
     <div class="header">Reply</div>

     Text:
     <textarea class="data" id="body" style="width: 100%" rows="15" /><br /><br/>
     <div style="color: #f00" class="status" />
     <img style="float: right" class="spinner" src="load.gif" />

     <input type="submit" class="submit" value="Create" />
   </div>


That's all that's necessary. The loader parses the controller-form element to figure out what to tell the controller, and then it parses #reply for things with the class data, and passes their values as POST-data to the controller.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
'; DROP DATABASE;--
Posts: 3284
Joined: Thu Nov 22, 2007 9:38 am UTC
Location: Midwest Alberta, where it's STILL snowy
Contact:

Re: Coding: Hacks and Snippets

Postby '; DROP DATABASE;-- » Thu Dec 17, 2009 5:46 am UTC

TheChewanater wrote:Here's what I did:
You're leaking file handles all over the place. :|

I just wrote a Lua script to generate a Bash script, since I couldn't remember the syntax to do the job in Bash alone and didn't want to look up the LuaFilesystem documentation. Meh, it works. :P
poxic wrote:You suck. And simultaneously rock. I think you've invented a new state of being.

fzort
Posts: 8
Joined: Thu Jan 24, 2008 8:30 pm UTC

Re: Coding: Hacks and Snippets

Postby fzort » Wed Dec 23, 2009 1:30 pm UTC

Back when I was young and stupid, I used to think I was clever because I wrote stuff like this (gcc- and unix-specific):

Code: Select all

main(c, v) char *v[]; {
    int dumplin(p) char *p; {
        p && *p && (dumplin(p + 1), *p == 90 ? ({char **q = v;
        do printf(*v, 34, *q++, 34, 10); while (*q); 1;}) : putchar(*p));
    }
    !--c ? main(0, (char *[]){
"%c%s%c,%c",
"}",
";)}    ",
";0        ",
"/* DEHCAERTON */        ",
" }        ",
";)01(rahctup ,)--ps*(nilpmud :pop            ",
";eunitnoc ;++p* = ps++* :hsup            ",
";])kcats < ps( + p*![)} 0 ,pop&& ,hsup&& {)][* diov((* otog            ",
"{ )1( elihw        ",
";)niam ,11(langis        ",
";kcats = ps** ,} 0 = ]0[ { = ]08[kcats* ,1 + v = p** rahc        ",
"{( : )0(tixe ? 01 == c : )} ,0    ",
"Z",
" {)][* rahc( ,0(niam ? c--!    ",
"}    ",
" ;))p*(rahctup : )};1 ;)q*( elihw ;)01 ,43 ,++q* ,43 ,v*(ftnirp od        ",
";v = q** rahc{( ? 09 == p* ,)1 + p(nilpmud( && p* && p        ",
" { ;p* rahc )p(nilpmud tni    ",
" { ;][v* rahc )v ,c(niam",

    0, }) : c == 10 ? exit(0) : ({
        char **p = v + 1, *stack[80] = { [0] = 0 }, **sp = stack;
        signal(11, main);
        while (1) {
            goto *((void *[]){ &&push, &&pop, 0 })[!*p + (sp < stack)];
            push: *++sp = *p++; continue;
            pop: dumplin(*sp--), putchar(10);
        }
        /* NOTREACHED */
        0;
    });
}


It's a quine. I must've been reading on gcc extensions at the time, thus the pointers to labels. Luckily, I grew up.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Hacks and Snippets

Postby headprogrammingczar » Wed Dec 23, 2009 2:44 pm UTC

The indenting...it hurts...
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Hacks and Snippets

Postby PM 2Ring » Wed Dec 23, 2009 2:58 pm UTC

Those wacky GNU dudes like this style, with the block contents aligned to the braces.

Code: Select all

int double(int a)
    {
     return a + a;
     }

I hates it.

Random832
Posts: 2525
Joined: Wed Oct 10, 2007 4:38 pm UTC

Re: Coding: Hacks and Snippets

Postby Random832 » Wed Dec 23, 2009 4:01 pm UTC

PM 2Ring wrote:Those wacky GNU dudes like this style, with the block contents aligned to the braces.

Code: Select all

int double(int a)
    {
     return a + a;
     }

I hates it.


I thought the gnu style was to have the braces halfway between the block and the contents, except for function definitions (which are more or less normal, with the braces on their own line at the left edge and the contents indented).

Another little-known aspect is a line break before the function name - so you can do a search for /^foo/ to find the definition.

Code: Select all

int
foo(int bar)
{
    if(bar % 1)
      {
        do_something();
      }
}

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: Coding: Hacks and Snippets

Postby Rysto » Wed Dec 23, 2009 4:49 pm UTC

PM 2Ring wrote:Those wacky GNU dudes like this style, with the block contents aligned to the braces.

Code: Select all

int double(int a)
    {
     return a + a;
     }

I hates it.

That's Whitesmiths style, not GNU style. GNU style is even more incomprehensible. I have a suspicion that they chose it because only emacs can automatically indent things that way.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Hacks and Snippets

Postby headprogrammingczar » Thu Dec 24, 2009 2:41 am UTC

Writing code in a hard-to-read style just so it can be more easily searched is an idiotic practice. That's a failing of the editor, not the coding style. The only machine you should ever write compiled code to is the compiler.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Thu Dec 24, 2009 2:54 am UTC

Also, this is blasphemy, especially for exemple code on the GTK+ site.

Code: Select all

static gboolean delete_event( GtkWidget *widget,
                              GdkEvent  *event,
                              gpointer   data )
{


I dunno, does anyone actually add new lines like this, for EVERY argument?
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Thu Dec 24, 2009 3:14 am UTC

TheChewanater wrote:Also, this is blasphemy, especially for exemple code on the GTK+ site.

Code: Select all

static gboolean delete_event( GtkWidget *widget,
                              GdkEvent  *event,
                              gpointer   data )
{


I dunno, does anyone actually add new lines like this, for EVERY argument?


It does come with some perks. It's much easier to alter the argument list, inserting at a specific point, and going to a specific argument.

Readability also increases quite a bit, especially with non-trivial types. Compare:

Code: Select all

void foobar(int * const foo, void (*bar)(void*, int const* const), void (*baz)(int, const char *, void (*)()));
void foobar(int * const foo,
            void (*bar)(void*, int const* const),
            void (*baz)(int, const char *, void (*)()));
void foobar(int * const foo,
            void (*bar)(void*,
                        int const* const),
            void (*baz)(int,
                        const char *,
                        void (*)()));


Also, removing say "int b" from a list that looks like this:

Code: Select all

void foobar(int a, int b, int c,
            int d, int e, int f,
            int g, int h, int z);


Would mean
  1. Removing int b
  2. Moving int d to the end of the first line
  3. Moving int g to the end of the second line

But removing it from

Code: Select all

void foobar(int a,
            int b,
            int c,
            int d,
            int e,
            int f,
            int g,
            int h,
            int z);


Would simply be a matter of removing the line.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
Area Man
Posts: 256
Joined: Thu Dec 25, 2008 8:08 pm UTC
Location: Local

Re: Coding: Hacks and Snippets

Postby Area Man » Thu Dec 24, 2009 8:04 am UTC

TheChewanater wrote:I dunno, does anyone actually add new lines like this, for EVERY argument?
I do sometimes, to put a comment after each to explain the purpose of the args.
Bisquick boxes are a dead medium.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Thu Dec 24, 2009 4:59 pm UTC

Area Man wrote:
TheChewanater wrote:I dunno, does anyone actually add new lines like this, for EVERY argument?
I do sometimes, to put a comment after each to explain the purpose of the args.

Well, the Gtk example code does all the time, without commenting on each and every argument. It would probably be easier to read if they had syntax highlighting.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
Earlz
Gets Obvious Implications
Posts: 785
Joined: Sat Jun 09, 2007 8:38 am UTC
Location: USA
Contact:

Re: Coding: Hacks and Snippets

Postby Earlz » Thu Dec 24, 2009 5:38 pm UTC

TheChewanater wrote:
Area Man wrote:
TheChewanater wrote:I dunno, does anyone actually add new lines like this, for EVERY argument?
I do sometimes, to put a comment after each to explain the purpose of the args.

Well, the Gtk example code does all the time, without commenting on each and every argument. It would probably be easier to read if they had syntax highlighting.


I do this only whenever having all of the arguments on one line would make me horizontally scroll..
My new blag(WIP, so yes it's still ugly..)
DEFIANCE!
Image
This is microtext. Zooming in digitally makes it worse. Get a magnifying glass.. works only on LCD

User avatar
b.i.o
Green is the loneliest number
Posts: 2519
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: Coding: Hacks and Snippets

Postby b.i.o » Fri Dec 25, 2009 6:42 pm UTC

TheChewanater wrote:I dunno, does anyone actually add new lines like this, for EVERY argument?


I do it sometimes when I have more than one line's worth of arguments. It keeps things organized nicely. I don't do it for things with just a few arguments though.

Posi
Posts: 111
Joined: Mon Jul 16, 2007 6:08 am UTC

Re: Coding: Hacks and Snippets

Postby Posi » Tue Dec 29, 2009 4:26 am UTC

Earlz wrote:
TheChewanater wrote:
Area Man wrote:
TheChewanater wrote:I dunno, does anyone actually add new lines like this, for EVERY argument?
I do sometimes, to put a comment after each to explain the purpose of the args.

Well, the Gtk example code does all the time, without commenting on each and every argument. It would probably be easier to read if they had syntax highlighting.


I do this only whenever having all of the arguments on one line would make me horizontally scroll..

I have the text editor wrap it and indent it, and leave the actual code 42 screens wide.

Unless there is a really messed up type, like the one that was shown earlier.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Hacks and Snippets

Postby Xeio » Tue Dec 29, 2009 5:28 am UTC

Posi wrote:I have the text editor wrap it and indent it, and leave the actual code 42 screens wide.
Oh, you're THAT bastard.

(I didn't know there were people that actually used word wrap when programming...)

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Hacks and Snippets

Postby TheChewanater » Tue Dec 29, 2009 5:35 am UTC

Posi wrote:I have the text editor wrap it and indent it, and leave the actual code 42 screens wide.

I hate word wrap. It messes up the whole thing. For example, the following looks really bad (assuming your browser window is less than about 1500 pixels wide).

Code: Select all

<body>
   <div>
      <span>
         blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
      </span>
   </div>
</body>
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Hacks and Snippets

Postby You, sir, name? » Tue Dec 29, 2009 6:56 am UTC

TheChewanater wrote:
Posi wrote:I have the text editor wrap it and indent it, and leave the actual code 42 screens wide.

I hate word wrap. It messes up the whole thing. For example, the following looks really bad (assuming your browser window is less than about 1500 pixels wide).

Code: Select all

<body>
   <div>
      <span>
         blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
      </span>
   </div>
</body>


I don't see why it shouldn't be possible to create word wrap that is aware of indentation.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
headprogrammingczar
Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

Re: Coding: Hacks and Snippets

Postby headprogrammingczar » Tue Dec 29, 2009 2:44 pm UTC

Eclipse does it...
inb4 Eclipse hate
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 11 guests