Coding: Fleeting Thoughts

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

Moderators: phlip, Moderators General, Prelates

afarnen
Posts: 157
Joined: Mon May 05, 2008 12:12 pm UTC

Re: Coding: Fleeting Thoughts

Postby afarnen » Wed Jan 06, 2010 5:25 am UTC

Cosmologicon wrote:python does it too, of course....

Anyway, customizable syntax is great until you want to collaborate in any way, or use someone else's code from the web.

True. It seems like more of a gimmick than useful. It'd be difficult to standardize. However, some sort of language-independent preprocessor could be more useful.

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

Re: Coding: Fleeting Thoughts

Postby Area Man » Wed Jan 06, 2010 8:28 am UTC

afarnen wrote:some sort of language-independent preprocessor could be more useful.
You mean like m4, awk and sed ...? someone should invent those ;)

User avatar
InkL0sed
Posts: 205
Joined: Wed Sep 10, 2008 3:46 am UTC

Re: Coding: Fleeting Thoughts

Postby InkL0sed » Wed Jan 06, 2010 4:39 pm UTC

stephentyrone wrote:
lulzfish wrote:I would add Lua's thing where:

Code: Select all

{itemOne, itemTwo, itemThree,}

is valid. (It's the last comma, it wouldn't be valid in any other language I've ever used)


Huh? Hell, that's valid in C.


The last comma? Since when?

User avatar
RoadieRich
The Black Hand
Posts: 1037
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Behind you

Re: Coding: Fleeting Thoughts

Postby RoadieRich » Wed Jan 06, 2010 5:16 pm UTC

lulzfish wrote:I would add Lua's thing where:

Code: Select all

{itemOne, itemTwo, itemThree,}

is valid. (It's the last comma, it wouldn't be valid in any other language I've ever used)

It's valid py3k, and you can do the same in python2 if you use lists, tuples or dicts instead of the set notation.

Code: Select all

>>> [1,2,3,]
[1, 2, 3]
>>> (1,2,3,)
(1, 2, 3)
>>> {1:1,2:2,3:3,}
{1: 1, 2: 2, 3: 3}
You can even throw an extra comma into the end of function defs and calls:

Code: Select all

>>> def fn(itemOne, itemTwo, itemThree,):
    return itemOne + itemTwo + itemThree

>>> fn(1,2,3,)
6
In fact, you need it to create a one-element tuple using tuple notation:

Code: Select all

>>> type((1))
<type 'int'>
>>> type((1,))
<type 'tuple'>
73, de KE8BSL loc EN26.

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

Re: Coding: Fleeting Thoughts

Postby Random832 » Wed Jan 06, 2010 6:58 pm UTC

InkL0sed wrote:
stephentyrone wrote:
lulzfish wrote:I would add Lua's thing where:

Code: Select all

{itemOne, itemTwo, itemThree,}

is valid. (It's the last comma, it wouldn't be valid in any other language I've ever used)


Huh? Hell, that's valid in C.


The last comma? Since when?


Since ANSI, at least.

Code: Select all

          initializer:
                  assignment-expression
                  {  initializer-list }
                  {  initializer-list , }
#                                      ^
          initializer-list:
                  initializer
                  initializer-list ,  initializer


Not allowed for function calls, though.

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

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Wed Jan 06, 2010 7:02 pm UTC

InkL0sed wrote:
stephentyrone wrote:
lulzfish wrote:I would add Lua's thing where:

Code: Select all

{itemOne, itemTwo, itemThree,}

is valid. (It's the last comma, it wouldn't be valid in any other language I've ever used)


Huh? Hell, that's valid in C.


The last comma? Since when?

I see it all the time in the Source Engine code.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Thu Jan 07, 2010 5:05 am UTC

I have done it.

My compression program that I have been working on for the past few days is now at a point where it beats gzip -9 on my system's /usr/share/dict/words file.

gzip, naturally, easily beats it for speed, but I haven't been optimizing it for speed. With some better algorithms I should be able to achieve a nice speed up (less O(n) string searches). I need to first finish working on improving the compression ratio.

Yeah, it's slow, and could be better. emacs.tar is a tar of my copy of emacs for windows, and weighs in at 138.6 megs. My program took 61 minutes to compress emacs.tar down to 45.4 megs. Before my lastest improvement, it compressed it down to 61 megs in about a minute...

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

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Jan 07, 2010 1:47 pm UTC

How does it do compared to bzip2?
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Thu Jan 07, 2010 6:04 pm UTC

You, sir, name? wrote:How does it do compared to bzip2?

For /usr/share/dict/words, bzip2 -9 actually performs worse than gzip -9; it is a strange file.

For some HTML, gzip -9 currently does twice as good as my program; I think I should be a able to close that gap once I finish the feature that I'm working on.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Thu Jan 07, 2010 7:15 pm UTC

This code is insane, but it is a bit nicer than what I had before.

Warning: Exposing the code below may be harmful to your health
Spoiler:
Image

Code: Select all

void Compressor::go() {
  int readByte;
  int symbolLeft;

  // goto is good for state machines, right?

  // State 0: Using normal model
 state0:
  readByte = fgetc(srcFile);
  // Write EOF to file
  if (readByte == EOF) {
    coder->encodeSymbol(1, control);
    goto end;
  } else {
    coder->encodeSymbol(0, control);
  }
  // Check for symbol match
  if (window->matchFound(readByte)) {
    // Starting a symbol
    coder->encodeSymbol(SYMBOL2, normal);
    // Right now we know that there is only one more left
    symbolLeft = 1;
    // We store absolute length difference from 3
    coder->encodeSymbol(symbolLeft+2-3, slength);
    // We must tell window that we have started matching
    window->startMatching();
    // Move to state 1
    goto state1;
  } else {
    // No match; encode normally
    coder->encodeSymbol(readByte, normal);
    logByte();
    // We need to give window this byte for its window
    window->pushSymbol(readByte);
    // Now we loop
    goto state0;
  }

  // State 1: Using symbol mode
 state1:
  // We encode the byte
  coder->encodeSymbol(readByte, window);
  logByte();
  symbolLeft--;
  if (symbolLeft == 0) {
    // We are done with symbol mode
    goto state0;
  } else {
    // Fetch the next byte (we know the file isn't done yet)
    readByte = fgetc(srcFile);
    goto state1;
  }

 end:
  // We are done
  coder->flush();
  printStats();
}

User avatar
lulzfish
Posts: 1214
Joined: Tue Dec 16, 2008 8:17 am UTC

Re: Coding: Fleeting Thoughts

Postby lulzfish » Thu Jan 07, 2010 7:32 pm UTC

Well, that's quite interesting, but since I don't automatically generate C code ever, it's not as useful in the end as Lua or Python having it.

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

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Jan 07, 2010 8:19 pm UTC

lulzfish wrote:Well, that's quite interesting, but since I don't automatically generate C code ever, it's not as useful in the end as Lua or Python having it.


But why would you want to generate high-level code? Seems horrible and wrong somehow.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Thu Jan 07, 2010 9:10 pm UTC

You, sir, name? wrote:
lulzfish wrote:Well, that's quite interesting, but since I don't automatically generate C code ever, it's not as useful in the end as Lua or Python having it.


But why would you want to generate high-level code? Seems horrible and wrong somehow.

C = portable assembler

User avatar
lulzfish
Posts: 1214
Joined: Tue Dec 16, 2008 8:17 am UTC

Re: Coding: Fleeting Thoughts

Postby lulzfish » Thu Jan 07, 2010 11:02 pm UTC

You, sir, name? wrote:
lulzfish wrote:Well, that's quite interesting, but since I don't automatically generate C code ever, it's not as useful in the end as Lua or Python having it.


But why would you want to generate high-level code? Seems horrible and wrong somehow.

Well, you see...
I'm using Lua as a data language for 3D models. Since Blender is scripted in Python, I have a Python script automatically convert the model to a Lua script. My 3D application uses an embedded Lua interpreter to read the script, which creates the model as a set of Lua tables, and then the data is copied into C++ arrays for the 3-language hat trick.

I'm probably going to write a proper model format someday, but for now Lua is working amazingly. It's human-readable, and I can syntax-check it by calling the standalone Lua interpreter.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Fri Jan 08, 2010 2:23 am UTC

Lookup tables help a lot. They brought the runtime of my program down from 38 minutes to 1 minute 45 seconds for a large file.

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: Fleeting Thoughts

Postby b.i.o » Fri Jan 08, 2010 7:31 am UTC

The built-in Python profiler (cProfile) is my new best friend.

Had two programs that were taking 1 minute and 3 minutes to run, respectively. Hackish optimizations on one function of the first brought the run time down to 1.5 seconds. Rewriting a badly written function on the second brought the run time down to 4.5 seconds. Much better.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Fri Jan 08, 2010 6:24 pm UTC

It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

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: Fleeting Thoughts

Postby TheChewanater » Fri Jan 08, 2010 7:58 pm UTC

Berengal wrote:http://www.google.com/search?hl=en&client=firefox-a&rls=com.ubuntu:en-US:unofficial&hs=PwJ&ei=8nZHS_maC8bO8QbBooyFAw&sa=X&oi=spell&resnum=0&ct=result&cd=1&ved=0CAYQBSgA&q=number+of+horns+on+a+unicorn+acre+in+teaspoons+per+lightyear&spell=1


Google is funny.

I'm stealing this for the "Count to a million" thread.
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: Fleeting Thoughts

Postby You, sir, name? » Fri Jan 08, 2010 8:37 pm UTC

Google makes mathematics beautiful: e^(ln(-number of horns on a unicorn)) + number of horns on a unicorn
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Wed Jan 13, 2010 5:26 am UTC

Embedding concatenative programming in a language not designed for it is interesting. You want to reuse already existing functions, but the functions aren't designed for concatenative code. One must confront several problems: How many arguments to pass to functions? How should the arguments be ordered? If your language doesn't support multiple return values, how do make it so people can factor their definitions? Do you do all of the handling at runtime, or do you do it at compile time? Etc.

After working on this in Clojure, I can now write the function square in a weird way:

Code: Select all

(def square (con 2 * range 'odd? filter '+ reduce))

I can even do pointless factorings!

Code: Select all

(defcon rofp 1 2 range 'odd? filter '+)
(def square (con 2 * rofp reduce))

The syntax for defcon needs some polish, I'm overloading the meaning of quote, the implementation could do more error checking, I should write a small library of useful concatenative functions, I failed to do TDD (or write any tests yet), but it is something.

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: Fleeting Thoughts

Postby TheChewanater » Thu Jan 14, 2010 4:03 am UTC

I don't know why, but I wrote this out of boredom. This absolutely horrendous 'algorithm' in C(++), for lack of a better term, produces a neat pattern. I wrote it in Allegro 4.2, but it should be trivial to port to another library. In fact, I ported it to JavaScript, but it crashed Gecko. :) With a little debugging power, I found that it draws over 90,000 pixels but less than half of that end up being drawn, so it must be going over them a lot.

Code: Select all

   //SCREEN_W and SCREEN_H (not used) are both 512 pixels and represent the width and height of the window

   int red = makecol(255, 0, 0);
   
   for (int y = -SCREEN_W; y < SCREEN_W; y += 50)
   {
      for (int d = SCREEN_W / 2; d; d *= -0.25)
      {
         for (int x = 0; x < SCREEN_W / d; x ++)
         {
            for (int blah = 2; blah < 10; blah ++)
            {
               putpixel (screen, x + y / SCREEN_W, (x ^ blah) + y, red);
            }
         }
      }
   }


Edit: fix'd variable name
Last edited by TheChewanater on Thu Jan 14, 2010 4:37 am UTC, edited 2 times in total.
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: Fleeting Thoughts

Postby phlip » Thu Jan 14, 2010 4:31 am UTC

TheChewanater wrote:x ^ pow

Given your variable names, I don't think that operator does what you think it does.

Kinda interesting result though:
tmp.png
tmp.png (1.33 KiB) Viewed 4743 times
Spoiler:
Non-library-dependent Python version of the code, for the curious:

Code: Select all

#!/usr/bin/python
width, height = 512,512
image = [[False] * width for y in xrange(height)]

d = width/2
ds = []
while d:
   ds.append(d)
   d = -d/4

for y in xrange(-width,width,50):
   for d in ds:
      for x in xrange(0, width/d):
         for pow in xrange(2,10):
            x1 = x + y / width
            y1 = (x ^ pow) + y
            if x1 >= 0 and y1 >= 0 and x1 < width and y1 < height:
               image[y1][x1] = True

fp = open("tmp.pbm", "w")
fp.write("P1\n") # ASCII-mode monochrome bitmap
fp.write("%s %s\n" % (width, height))
fp.write("\n".join(" ".join(("1" if pixel else "0") for pixel in row) for row in image))
fp.close()


[edit]
Actually, I don't think the result is the same... C's integer division seems to round towards 0 (so "x + y / width" is pretty much always just x, except on the very first iteration of the "y" loop, when it's x - 1), but Python's seems to round towards negative infinity (so "x + y / width" is x-1 half the time and x half the time)
[edit again]
It looks like the only difference, though, is that in your version, the chain that goes from the top left corner to the bottom right corner, and all the ones above and to the right of it, are offset by a pixel. Everything else is the same.

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: Fleeting Thoughts

Postby TheChewanater » Thu Jan 14, 2010 4:35 am UTC

phlip wrote:
TheChewanater wrote:x ^ pow

Given your variable names, I don't think that operator does what you think it does.

Actually, I just changed it a few times without changing the variable names. I accidentally put ^ (xor) when I was trying to figure out powers, but it gave an interesting result so I kept it even after I remembered what it was.
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.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Sat Jan 16, 2010 12:28 am UTC

Sudoku is too easy. After throwing some of hardest ones list on wikipedia, the longest my unoptimized, rather simple solution in Clojure took 960 milliseconds to solve.

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

Re: Coding: Fleeting Thoughts

Postby headprogrammingczar » Sat Jan 16, 2010 3:27 pm UTC

Those 'hard' sudoku problems are supposed to be difficult for humans. It goes without saying that any game with an easily enumerable solution-space is too easy to merit analysis.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sat Jan 16, 2010 3:46 pm UTC

Depends on what you consider easily enumerable. Sudoku is NP complete.

You should try some of the 17-hint games. There's a 16-hint game with only two solutions as well, if your program can solve non-unique games.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Sat Jan 16, 2010 6:01 pm UTC

Actually, the 960 msec problem only takes about 660 msec once the JVM warms up.

Berengal wrote:Depends on what you consider easily enumerable. Sudoku is NP complete.

You should try some of the 17-hint games. There's a 16-hint game with only two solutions as well, if your program can solve non-unique games.

The few 17-hint games that I have found are really easy...

I'm amazed at how fast little more than brute force can solve them (or maybe I should be amazed at modern machines...)

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sat Jan 16, 2010 6:32 pm UTC

It's true. A dancing links implementation will chew through any sudoku in no time at all. The one I made found all 250-something solutions to a 12-hint game in half a second...
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Sat Jan 16, 2010 8:42 pm UTC

Hmm...
Image

A compelling case for the Borg?

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Coding: Fleeting Thoughts

Postby Berengal » Sat Jan 16, 2010 10:18 pm UTC

Image
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

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

Re: Coding: Fleeting Thoughts

Postby fazzone » Sat Jan 16, 2010 11:44 pm UTC

qbg wrote:Sudoku is too easy. After throwing some of hardest ones list on wikipedia, the longest my unoptimized, rather simple solution in Clojure took 960 milliseconds to solve.

Which one exactly did you do? I wonder how my simple backtracking solver in C would stand up.
*/

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Sat Jan 16, 2010 11:54 pm UTC

fazzone wrote:
qbg wrote:Sudoku is too easy. After throwing some of hardest ones list on wikipedia, the longest my unoptimized, rather simple solution in Clojure took 960 milliseconds to solve.

Which one exactly did you do? I wonder how my simple backtracking solver in C would stand up.

Code: Select all

. . 1 | . . 4 | . . . 
. . . | . 6 . | 3 . 5 
. . . | 9 . . | . . . 
------+-------+------
8 . . | . . . | 7 . 3 
. . . | . . . | . 2 8 
5 . . | . 7 . | 6 . . 
------+-------+------
3 . . | . 8 . | . . 6 
. . 9 | 2 . . | . . . 
. 4 . | . . 1 | . . . 

qbg
Posts: 586
Joined: Tue Dec 18, 2007 3:37 pm UTC

Re: Coding: Fleeting Thoughts

Postby qbg » Sun Jan 17, 2010 4:49 am UTC

The concatenative paradigm can be quite awesome.

For instance, the y combinator in my DSL/whatever (also why lisp macros are awesome)

Code: Select all

(defword ycomb dup call)

Also, since extract function is cut and paste, I can turn:

Code: Select all

(defcon foo [n]
  [swap dup [swap] dip 0 = [drop] [[dup println 1 -] dip dup call] if] dup call)

Into:

Code: Select all

(defword ycomb dup call)
(defword print-dec [dup println 1 -] dip)
(defword over swap dup [swap] dip)
(defword zero-test over 0 =)
(defcon foo [n] [zero-test [drop] [print-dec ycomb] if] ycomb)

Although it is longer than the code it replaced, it is more understandable and more reusable.

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

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Thu Jan 21, 2010 9:13 pm UTC

If you have a single linked list in C that is defined like this:

Code: Select all

struct list {
  struct list *next;
  void *data;
};


It is valid to do this:

Code: Select all

  struct list * foo = get_a_list();
  while(foo) {
     do_something(foo);
     foo = *(struct list**)foo;
  }


I'm not sure why you would want to write '*(struct list**)foo' instead of the shorter 'foo->next', but the possibility appeals to me.

That is all.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

masher
Posts: 821
Joined: Tue Oct 23, 2007 11:07 pm UTC
Location: Melbourne, Australia

Re: Coding: Fleeting Thoughts

Postby masher » Fri Jan 22, 2010 3:24 am UTC

Code: Select all

try
{
   return true;
}
finally
{
   return false;
}


Argh!!

Seen here: http://neil.fraser.name/news/2009/10/27/

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

Re: Coding: Fleeting Thoughts

Postby fazzone » Fri Jan 22, 2010 1:22 pm UTC

Wow, I was getting times of about 5 to 6 seconds. What kind of algorithm did you implement?
*/

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

Re: Coding: Fleeting Thoughts

Postby phlip » Fri Jan 22, 2010 1:28 pm UTC

You, sir, name? wrote:It is valid

I'm 99% sure it's undefined according to the spec... but it'll probably do what you expect on most platforms.

Code: Select all

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

stephentyrone
Posts: 778
Joined: Mon Aug 11, 2008 10:58 pm UTC
Location: Palo Alto, CA

Re: Coding: Fleeting Thoughts

Postby stephentyrone » Fri Jan 22, 2010 3:21 pm UTC

phlip wrote:
You, sir, name? wrote:It is valid

I'm 99% sure it's undefined according to the spec... but it'll probably do what you expect on most platforms.

§6.7.2.1, Paragraph 13:
A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

That said:

Code: Select all

  while(foo) {
     do_something(foo);
     foo = foo->next;
  }

is much more considerate, and won't be broken by compilers that are particularly zealous about strict-aliasing rules (GCC, I'm looking at you).
GENERATION -16 + 31i: The first time you see this, copy it into your sig on any forum. Square it, and then add i to the generation.

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

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Fri Jan 22, 2010 5:50 pm UTC

stephentyrone wrote:
phlip wrote:
You, sir, name? wrote:It is valid

I'm 99% sure it's undefined according to the spec... but it'll probably do what you expect on most platforms.

§6.7.2.1, Paragraph 13:
A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

That said:

Code: Select all

  while(foo) {
     do_something(foo);
     foo = foo->next;
  }

is much more considerate, and won't be broken by compilers that are particularly zealous about strict-aliasing rules (GCC, I'm looking at you).


Yeah, this --^.
It's the same mechanism that allows you to do struct 'inheritance', like

Code: Select all

struct foo {
  // struct elements go here
};

struct bar {
  struct foo base;
  // struct elements go here
}

// ...

struct bar *b = get_bar();
struct foo *f = (struct foo*) b; /* This is valid */


(Semi-)object oriented libraries like glib/gtk+ wouldn't function without this quirk.
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

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

Re: Coding: Fleeting Thoughts

Postby phlip » Sat Jan 23, 2010 12:59 am UTC

Huh... well then. I had a vague feeling something like that existed, but I thought I was misremembering (maybe getting confused with pointers-to-unions, which can be cast to pointers-to-union-members). But I wasn't sure, and was too lazy to look it up, hence the "99%".

Code: Select all

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


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 10 guests