Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Atom
Apr 6, 2005

by Y Kant Ozma Post

chocojosh posted:

In all seriousness then, how would you encode N different options that can be on simultaneously? I always assumed the bitmask would work (and I would go so far to say that it is a simple and clear solution that should be efficient enough for small cases, n <= 8 or n <= 32).

Bitmask if all the options are true false, otherwise use quaternary or octal. If aiming for theoretical maximum compactness rather than computational complexity, you would have to do some variable base poo poo.

edit: sorry I didn't notice this was two pages ago!

Atom fucked around with this message at 09:29 on May 7, 2008

Adbot
ADBOT LOVES YOU

Incoherence
May 22, 2004

POYO AND TEAR

MEAT TREAT posted:

:aaaaa:
Wow this is so simple that it never occurred to me. I always thought ++i was a matter of style. Is it safe to assume that modern compilers do this automatically now? Except in the case of the iterator you mentioned.
It's possible that a present-day compiler could optimize for (int i = 0; ...; i++) into ++i, but probably not any sort of class (the previously mentioned example where some rear end in a top hat defines operator++() and operator++(int) to do different things).

floWenoL
Oct 23, 2002

crazypenguin posted:

I never understood why they chose to make ++i and i++ different functions, rather than just having a single ++ function and just change when it gets called relative to when it is evaluated.

This is C++'s idea of flexibility. :rolleye:

floWenoL
Oct 23, 2002

Incoherence posted:

It's possible that a present-day compiler could optimize for (int i = 0; ...; i++) into ++i, but probably not any sort of class (the previously mentioned example where some rear end in a top hat defines operator++() and operator++(int) to do different things).

No, iter++ should be optimized just fine most of the time, given that iterators are usually part of templated class (and hence the function definition is visible) and operator++s are usually short enough to be inlined. A simple dataflow analysis pass should enable the compiler to conclude that the copied variable is not used and therefore can be omitted, assuming the copy constructor etc. have no side effects. Indeed, for the following code gcc 4.x (which doesn't exactly emit the fastest code) still manages to generate the same code for pre() and post() with -O2:

code:
#include <vector>

int pre(const std::vector<int> &v) {
  int x = 0;
  for (std::vector<int>::const_iterator i = v.begin();
       i != v.end();
       ++i) {
    x += *i;
  }
  return x;
}

int post(const std::vector<int> &v) {
  int x = 0;
  for (std::vector<int>::const_iterator i = v.begin();
       i != v.end();
       i++) {
    x += *i;
  }
  return x;
}

TSDK
Nov 24, 2003

I got a wooden uploading this one

floWenoL posted:

A simple dataflow analysis pass should enable the compiler to conclude that the copied variable is not used and therefore can be omitted, assuming the copy constructor etc. have no side effects.
(Emphasis mine)

That's the biggie though, and I'm not sure that's common to a lot of compilers.

I'm willing to bet that the same code was generated on each for the vector example because the iterator is a simple typedef to a pointer. What happens with a std::list or std::map?

accipter
Sep 12, 2003
My officemate isn't really that experienced with coding, but I am going to make fun of her anyway. I entered the office one day to find a little note card on the ground with the following:

code:
  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  q  r  s  t  u  v  w  x  y  z
  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  Q  R  S  T  U  V  W  X  Y  Z
  aa bb cc dd ee ff
Apparently she had multiple for loops that she used a separate variable for each. Each of the results were are named differently, instead of using a two-dimensional array.

chocojosh
Jun 9, 2007

D00D.
Some awesome code I saw today:

code:
dataRow[columnName]=  IIF(osui.GetString(optionSystemName)==null,"(N/A)",osui.GetString(optionSystemName));


protected string IIF(bool expression,string returnValue1,string returnValue2)
		{
			if (expression==true)
			{
				return returnValue1;
			}
			else
			{
				return returnValue2;
			}						 
		}

We couldn't have just used the ? operator?

more falafel please
Feb 26, 2005

forums poster

Standish posted:

I'd be surprised if it could optimize that for std::iterators, remember the STL is just another library as far as the compiler is concerned -- from the compiler's point of view, it doesn't know anything about iterator semantics and std::iterator::operator++() (the prefix overload) and std::iterator::operator++(int) (the postfix overload) are completely distinct functions which could have completely different sideeffects.

In contrast, int is a built-in type so the compiler does know exactly when it's safe to substitute ++int for int++.

Well, it depends on the iterator. I think every implementation of std::vector<T> just typedefs iterator to T* (except for vector<bool>, but that's a whole other story), because it needs to have exactly the semantics of a pointer to an element in the vector. So, in many cases, there is not operator++() or operator++(int) functions. The standard specifies only that the operations ++it and it++ are legitimate, not that they're implemented as functions.

And since (in most cases, anyway) iterators are associated with class templates like containers, the implementation is known at compile time, so the compiler would be able to inline std::list<T>::iterator::operator++/operator++(int) (as an example of an iterator type that does have to be implemented).

So the point is that the compiler is usually smarter than you. However, you should Say What You Mean, and since it++ has the semantics of returning the old value, you don't usually mean that.

Mr.Radar
Nov 5, 2005

You guys aren't going to believe this, but that guy is our games teacher.

chocojosh posted:

We couldn't have just used the ? operator?

The person who wrote that probably cut their teeth with VB6 and wasn't aware of the ?: operator. VB6 didn't have a dedicated short-circuiting inline conditional operator, but it included a (non-short-circuiting IIRC) IIF function that worked like the one you posted.

Mr.Radar fucked around with this message at 16:35 on May 7, 2008

Vanadium
Jan 8, 2005

Flobbster posted:

string is a template

basic_string is a template, string is a regular type :colbert:

Zombywuf
Mar 29, 2008

Flobbster posted:

And to stroke my e-penis a little, code like what I just wrote above pisses me off. It should be
code:
for(size_t i = 0; i < str.length(); i++)

ITYM:
code:
for (string::size_type i = 0; i < str.length(); ++i)

stack
Nov 28, 2000
This makes me cry
code:
@empty($someVar)

@isset($someVar)
What error are you trying to suppress? If the value doesn't exist they'll return false. isset() for the love of pete exists to check if a value 'is set'.

Also this hurts me
code:
if(!isset($bravo)) $blah = here($something);
elseif(isset($charlie)) $blah = here($charlie);
else $blah = nothere();
Whitespace is free goddamnit. A couple pairs of braces couldn't hurt either.

New code is committed daily that is littered with examples and uses of the above.

chocojosh
Jun 9, 2007

D00D.

Mr.Radar posted:

The person who wrote that probably cut their teeth with VB6 and wasn't aware of the ?: operator. VB6 didn't have a dedicated short-circuiting inline conditional operator, but it included a (non-short-circuiting IIRC) IIF function that worked like the one you posted.

Thanks :) The person who wrote the function also wrote a lot of our old ASP/VB6 SQL 2000 code. That would explain it.

chocojosh
Jun 9, 2007

D00D.

stack posted:

This makes me cry
code:
@empty($someVar)

@isset($someVar)
What error are you trying to suppress? If the value doesn't exist they'll return false. isset() for the love of pete exists to check if a value 'is set'.

Also this hurts me
code:
if(!isset($bravo)) $blah = here($something);
elseif(isset($charlie)) $blah = here($charlie);
else $blah = nothere();
Whitespace is free goddamnit. A couple pairs of braces couldn't hurt either.

New code is committed daily that is littered with examples and uses of the above.

Stack: I tend to code regularly like this:

code:
if(!isset($bravo))
   $blah = here($something)
elseif(isset($charlie)) 
   $blah = here($charlie)
else
   $blah = nothere();
My logic is I hate wasting an entire line just to show a brace. Also, I think that python has a specific syntax for an if statement in the form of
if <condition>: <statement>

floWenoL
Oct 23, 2002

TSDK posted:

(Emphasis mine)

That's the biggie though, and I'm not sure that's common to a lot of compilers.

Eh? By side effects I mean something like the copy constructor doing cout << "Copy constructor called!", which isn't common.

quote:

I'm willing to bet that the same code was generated on each for the vector example because the iterator is a simple typedef to a pointer. What happens with a std::list or std::map?

That's a good point, though; I had assumed vector iterators were wrappers around pointers instead of simple typedefs. I tried it with std::list and std::set, though, and the two are still identical.

Vanadium
Jan 8, 2005

It is implementation-defined :mad:

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

chocojosh posted:

Stack: I tend to code regularly like this:

code:
if(!isset($bravo))
   $blah = here($something)
elseif(isset($charlie)) 
   $blah = here($charlie)
else
   $blah = nothere();
My logic is I hate wasting an entire line just to show a brace.
Unless you're using an 80 line monitor for some terminal from the '80s, there is no such thing as "wasting a line."
That being said, not putting in braces for single line conditionals is probably OK, though I almost always put in braces so that I'm never caught doing something like
code:
if(!isset($bravo))
   $blah = here($something)
elseif(isset($charlie)) 
   $blah = here($charlie)
else
   $blah = nothere();
   somethingelse();
when I change my mind later.

duck monster
Dec 15, 2004

edit:nope

duck monster fucked around with this message at 08:51 on Sep 8, 2022

chocojosh
Jun 9, 2007

D00D.

Jethro posted:

Unless you're using an 80 line monitor for some terminal from the '80s, there is no such thing as "wasting a line."

To me, the line is wasted because it's more that I have to process. If I need to read 20 lines to understand a function instead of 15, then it is more difficult for me to process because it takes up more space, even if part of the space is only closing braces.

I also prefer clear code instead of very terse code. I basically like to make code "easy to read" because as Spolsky (lol) said, code is read much more often than it is written.

tef
May 30, 2004

-> some l-system crap ->
Have you read what you have written?

You're aguing against long functions in one paragraph and then arguing against terse code in the other.

Proper use of whitespace makes code easier to read, adding one brace to space code out is not a significant cognitive overhead.

tef fucked around with this message at 14:16 on May 8, 2008

stack
Nov 28, 2000

Jethro posted:

Unless you're using an 80 line monitor for some terminal from the '80s, there is no such thing as "wasting a line."
That being said, not putting in braces for single line conditionals is probably OK, though I almost always put in braces so that I'm never caught doing something like
code:
if(!isset($bravo))
   $blah = here($something)
elseif(isset($charlie)) 
   $blah = here($charlie)
else
   $blah = nothere();
   somethingelse();
when I change my mind later.

I was talking about PHP code in case it wasn't clear and the 'somethingelse();' line would be run for all three of the cases in the above example.

My biggest beef with my original example of the if/ifelse/else horror was that you have to unravel it either mentally or in the file every time you want to really understand it. It's not always a if/else statement that got balled up.

As for wasting a line. Is this so bad?
code:
if (!isset($bravo)) {
   $blah = here($something);
} elseif (isset($charlie)) {
   $blah = here($charlie);
} else {
   $blah = nothere();
}
It's an entire extra line longer when you put the braces on the same lines as the branch language. If I ended up writing something like this it would be a quick edit to add one or more new lines to any of the blocks. But I usually have to first untangle the knot of code to first find out if what I'm looking for is in there and then throw in some braces

It is my personal preference to use braces where ever a block of code could be defined by some form of branch but knotting up things into balls of whitespace-less blocks is very very wrong.

Mikey-San
Nov 3, 2005

I'm Edith Head!
code:
if (!isset($bravo)) {
   $blah = here($something);
} elseif (isset($charlie)) {
   $blah = here($charlie);
} else {
   $blah = nothere();
}
This kills me. The same-line braces are just so noisy. I don't mind collapsing if/else statements like this, but untangling/ignoring the superfluous braces drives me nuts.

Planning ahead with your code formatting is akin to premature optimization, in my book. If later you need to add extra lines (and therefore, braces), okay, you can do it later. Making it as readable as possible at the moment someone is looking at it is more important than worrying about how you might need to format it later.

edit: clarity

Mikey-San fucked around with this message at 22:11 on May 9, 2008

wolf_man
Oct 5, 2005

Nunez?
for smaller (i.e 1 line) if statments I do this
code:
if(!isset($bravo)) { $blah = here($something); }
elseif (isset($charlie)) { $blah = here($charlie); }
else { $blah = nothere(); }
3 lines, and I feel its still pretty readable.

longer statements I do the same as Mikey-San stack
code:
if (!isset($bravo)) { 
	$blah = here($something); 
} elseif (isset($charlie)) { 
	$blah = here($charlie); 
} else { 
	$blah = nothere(); 
}
my thinking is, if your not able to read my code, or at least figure it out, then you shouldnt be looking at it in the first place

wolf_man fucked around with this message at 19:06 on May 8, 2008

stack
Nov 28, 2000

wolf_man posted:

my thinking is, if your not able to read my code, or at least figure it out, then you shouldnt be looking at it in the first place

My thinking is if you're unable to adhere to a coding standard and go rogue-wolf (no pun intended) then you get your code audited and sent back to you for editing. Anyone going back to code, even their own code, months after it was written will have to stop to take a moment to re-read what's there. The time saved in mentally unraveling the knots is time spent finishing the project. It isn't always a simple small block like my example there are complex structures where the developer seemed to have lost the ability to hit both space and enter to format his code.

This thread is about what makes you laugh or cry and not to sway others to my side so you're welcome to your opinion on the matter.

At least no one had issues with the error suppression for isset() and empty(). ;p

Mikey-San
Nov 3, 2005

I'm Edith Head!

wolf_man posted:

longer statements I do the same as Mikey-San
code:
if (!isset($bravo)) { 
	$blah = here($something); 
} elseif (isset($charlie)) { 
	$blah = here($charlie); 
} else { 
	$blah = nothere(); 
}

I don't do that. I said I can't stand the superfluous braces.

quote:

my thinking is, if your not able to read my code, or at least figure it out, then you shouldnt be looking at it in the first place

My thinking is, in this order:

1. Adhere to the coding standards of the project you're working on.

2. If I don't strive for readability for others who might read my code later, I shouldn't be writing it in the first place.

Incoherence
May 22, 2004

POYO AND TEAR

wolf_man posted:

my thinking is, if your not able to read my code, or at least figure it out, then you shouldnt be looking at it in the first place
This is the kind of statement that allows people to justify all the stupid "I'm so clever" tricks. Yes, I COULD figure it out, but it will take me longer than if you'd just spent the 5 seconds to adhere to a decent coding standard in the first place.

Karanth
Dec 25, 2003
I need to finish Xenogears sometime, damn it.

Incoherence posted:

This is the kind of statement that allows people to justify all the stupid "I'm so clever" tricks. Yes, I COULD figure it out, but it will take me longer than if you'd just spent the 5 seconds to adhere to a decent coding standard in the first place.
This is my favorite response to people who love to wave their code-penis around by writing "I'm so clever" code:

Brian Kernighan posted:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are–by definition–not smart enough to debug it.
Burned by the original C hacker, bitches.

Real gangsta-rear end coders don't flex nuts
Cuz real gangsta-rear end coders know they got 'em. :c00lbert:

indigoe
Jul 29, 2003

gonna steal the show, you know it ain't no crime
Found today, written by a contractor. Some other things he writes makes me want to cry but I think this sums it up nicely.
php:
<?
if(isset($_GET['filename']))
{ 
    $loggedin = true;
    //etc
?>

noonches
Dec 5, 2005

It represents my lifestyle and stratus as a street savy irreverent youth, who lives large, and yet hungers for the next level in life.
Which part is a horror, the logging in from just setting a GET var, or the passing of a filename in the query string? They're both pretty awful.

zootm
Aug 8, 2006

We used to be better friends.
Setting someone as logged in just because they passed a filename in the query parameter seems to me to be the horror here.

Moetic Justice
Feb 14, 2004

by Fistgrrl
I don't know what you guys are talking about up there, just use


((!isset($bravo)) ? ($blah = here($something)) : ((isset($charlie)) ? ($blah = here($charlie)) : ($blah = nothere()));


and you can be rid of all that evil whitespace once and for all!

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Jungle Bus posted:

I don't know what you guys are talking about up there, just use


((!isset($bravo)) ? ($blah = here($something)) : ((isset($charlie)) ? ($blah = here($charlie)) : ($blah = nothere()));


and you can be rid of all that evil whitespace once and for all!

"whitespace" means any space, not just newlines. No whitespace would be:


((!isset($bravo))?($blah=here($something)):((isset($charlie))?($blah=here($charlie)):($blah=nothere()));


Which is why this whole argument was so weird - as far as I could tell, the original poster was complaining about "if(!isset($bravo))", which is hard to read because the "if" is all jammed up against the bracket, and then everyone argued about where the newlines should go.

EDIT: I think I'll leave those smilies there: they're pretty appropriate.

Mikey-San
Nov 3, 2005

I'm Edith Head!

JoeNotCharles posted:

"whitespace" means any space, not just newlines. No whitespace would be:


((!isset($bravo))?($blah=here($something)):((isset($charlie))?($blah=here($charlie)):($blah=nothere()));


Which is why this whole argument was so weird - as far as I could tell, the original poster was complaining about "if(!isset($bravo))", which is hard to read because the "if" is all jammed up against the bracket, and then everyone argued about where the newlines should go.

EDIT: I think I'll leave those smilies there: they're pretty appropriate.

I'm arguing about bracket placement HELLO GET IT RIGHT :argh:

To contribute:

I once worked on a project that had a feature for integrating with Flickr. We inherited the source base from an outsourced 1.0 (almost worthy of its own wtf thread), where instead of "Flickr", or even "Flicker", it was called "Ficker". Now whenever I think about Flickr, all I can hear in my head is "Ficker". :(

One day, I got so annoyed by seeing it that I burned an hour and got rid of it all. That was not a fun commit.

1337JiveTurkey
Feb 17, 2005

This'll probably horrify some posters, but I like:
code:
blah =	!isset(bravo)?	here(something) :
	isset(charlie)?	here(charlie) :
			nothere();
Conditions in one column, values in another and it's easy to quickly scan for what goes with what with the general else condition going at the end.

Spell
Nov 20, 2000

Eat your vegetables or you'll DIE!
I have a student who implemented iterators on his collection classes...
... and used for i = 0 to col.count-1 to enumerate the items in the collections instead of the iterators.

I guess he didn't like his own implementation.

Access Violation
Jul 21, 2003
I noticed this one in my own code just now after getting strange reports of the time display not working correctly.

//Get the date and time
$date = date("Y-m-d H:m:s");

Hmm, I wonder why the times were off by a little :mad:

Intel Penguin
Sep 14, 2007
hooray

the talent deficit posted:

A non-profit I do some work for had a webpage donated to them by a volunteer that looked like it was deployed in 1996. After multiple people walked away rather than try to work with the volunteer I got asked to take a look at it. Where a form appears on the page is instead this:

code:
<!-- CONTENT CONTAINER -->
  <div id='contentContainer' class='interactivePage'>
    <div id='contentBlock'>
      <!--
        All NAME REDACTED Interactive Pages are protected by password, and Secure Socket Layer Encryption.
        All code contained within them is protected by copyright.
        All attempts to bypass this security will be prosecuted to the fullest extent of the law.
      -->
    </div>
  </div>
<!-- CONTENT CONTAINER -->
So then, in the javascript, I find an eyeframe that's loading this (except it goes on for about six pages):

code:
PAR=window.parent;SYS=PAR.SYS;if(SYS){var v_file=g_page.substr(g_page.lastIndexOf('/')+1);
var v_nameArr=v_file.split('.');
var g_parent=SYS.c34317b7e1dbca8c615e3e8881734c00(v_nameArr[0]).parent;
if(g_parent&&typeof exec!='undefined'){g_parent.exec=exec;}}
if(typeof g_messColor!='undefined'){SYS.messColor=g_messColor;SYS.SIDHIS=new Array();
for(var i=0;i<g_sessHist.length;i++){SYS.SIDHIS[i]=g_sessHist[i];}}
2function submitForm(p_arr,p_page){var vPage=(p_page)?p_page:g_page;
var e208e29dbee8c7f3994a32f56e0be770=document.createElement('form');
e208e29dbee8c7f3994a32f56e0be770.method='post';
e208e29dbee8c7f3994a32f56e0be770.action=vPage;
for(var i=0;i<p_arr.length;i++)
{e208e29dbee8c7f3994a32f56e0be770.appendChild(formItem(p_arr[i].id,p_arr[i].value));}
var vBody=document.getElementsByTagName('body')[0];
vBody.appendChild(e208e29dbee8c7f3994a32f56e0be770);
e208e29dbee8c7f3994a32f56e0be770.submit();}
3function formItem(e8920696c8b3f148933d436606327e19,e03bb7688e58920a3532ef6fb0354013)
{var c22dbb8e41fd27f2d5c707a8f4551253=document.createElement('input');
c22dbb8e41fd27f2d5c707a8f4551253.type='text';
c22dbb8e41fd27f2d5c707a8f4551253.id=e8920696c8b3f148933d436606327e19;
c22dbb8e41fd27f2d5c707a8f4551253.name=e8920696c8b3f148933d436606327e19;
c22dbb8e41fd27f2d5c707a8f4551253.value=e03bb7688e58920a3532ef6fb0354013;
return c22dbb8e41fd27f2d5c707a8f4551253;}

Looks like he was 'encrypting' his page by running it through a filter that took out all white spacing and MD5'd every variable name.

theg sprank
Feb 3, 2008
pillage your village
I found these right next to each other in some code of mine today

code:
#define SIBLING(node) (((node)==((node)->parent->left)) ?\
                       ((node)->parent->right) : ((node)->parent->left))
#define GET_SIBLING(node) ((node) == (node)->parent->right ?\
			   (node)->parent->left : (node)->parent->right)
no idea what I was thinking

OddOne
Mar 18, 2008

by T. Finn
Also in the "no idea what I was thinking" department I created a troublesome footbullet that took me a few rounds of debugging to find, in part because I'm not normally this dumb (I swear!)...

I was calling my runtime-created controls' free-and-recreate functions within the onclick event handler they were instructed to use. So, while I was handling the click on one of them, I was also deallocating the control for which the event was assigned. BOOM, access violation, and a totally random one each time to further add to the debugging fun.

When I saw what I did I debated deinstalling the development tools - I know better than to free objects within their own event handlers but did it anyway.

Yes, I am a 'tard... :lol:

Amazing how much better it worked with the offending code moved out of the event handler...

Adbot
ADBOT LOVES YOU

Malderi
Nov 27, 2005
There are three fundamental forces in this universe: matter, energy, and enlighted self-interest.

1337JiveTurkey posted:

This'll probably horrify some posters, but I like:
code:
blah =	!isset(bravo)?	here(something) :
	isset(charlie)?	here(charlie) :
			nothere();
Conditions in one column, values in another and it's easy to quickly scan for what goes with what with the general else condition going at the end.

I have to say, I looked at that and instantly hated it. Then five seconds later I thought it was rather clever. I'd still never use it in production code, but it's a nice way of expressing it that, if it isn't someone's first time seeing it, should be very readable.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply