<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-2543858175797658864</id><updated>2011-12-01T12:52:02.320-05:00</updated><category term='protoman'/><category term='pcsx2'/><category term='starting blog'/><category term='earth'/><category term='bugs'/><category term='hex'/><category term='microVU'/><category term='brilliance'/><category term='cotton'/><category term='sleep'/><category term='playstation 2'/><category term='customizations'/><category term='NES'/><category term='gamedev'/><category term='genius'/><category term='c++0x'/><category term='video'/><category term='c++'/><category term='megaman'/><category term='cottonvibes'/><category term='comments'/><category term='greatness'/><category term='theory'/><category term='math'/><category term='bitwise tricks'/><category term='waste'/><category term='arrays'/><category term='static'/><category term='awesome'/><category term='programming'/><category term='word verification'/><category term='optimizations'/><category term='games'/><category term='Earth Day'/><category term='videogames'/><category term='VU'/><category term='cottonNES'/><category term='options'/><category term='life'/><category term='ps2'/><category term='emulation'/><category term='something'/><category term='misconceptions'/><category term='day'/><category term='energy'/><category term='lamdas'/><category term='discrete math'/><category term='shaders'/><category term='hacks'/><category term='graph theory'/><category term='coding'/><category term='fun'/><category term='references'/><category term='beginning'/><category term='recursion'/><title type='text'>Trash Can of Code</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>54</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-562068034308434976</id><published>2011-10-04T01:32:00.006-04:00</published><updated>2011-10-05T21:46:11.535-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Bitwise Set-Bit (#2)</title><content type='html'>In a &lt;a href="http://cottonvibes.blogspot.com/2010/07/bitwise-set-bit.html"&gt;past article&lt;/a&gt;, I've shown some ways to do this. This time I'll show you another way to do it that I just came up with.&lt;br /&gt;&lt;br /&gt;The problem:&lt;br /&gt;Return 1 if a 32bit integer is non-zero, else return 0. The return-type should be a 32bit integer.&lt;br /&gt;&lt;br /&gt;The Typical Solution:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;s32 setBit(s32 x) {&lt;br /&gt;    return x ? 1 : 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The Cooler Solution:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;s32 setBit(s32 x) {&lt;br /&gt;    return !!x; // Forces it to a bool which is 1 or 0&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The Bitwise Solution:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;s32 setBit(s32 x) {&lt;br /&gt;    return (u32)(x | -x) &gt;&gt; 31;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The last one works because any non-zero integer will have its sign bit set either when negated or normally (if its already negative). The only number that won't have its sign bit set after ORing these results is 0. So we just logically-shift right by 31 to get a 1 or 0 value, which is what we wanted :D&lt;br /&gt;&lt;br /&gt;Note 1: The bitwise trick in this case is not preferred, instead you should use the 'typical' or 'cool' solution, since the compiler will be able to optimize it better for the given architecture. On x86 there is a SETcc instruction which can be used which is likely faster than doing the bitwise trick since its less operations. This trick may still be useful to know though in-case you're doing asm or compiler work with some architecture that doesn't have a SETcc-like instruction (and you wish to avoid jumps). Although the method from my &lt;a href="http://cottonvibes.blogspot.com/2010/07/bitwise-set-bit.html"&gt;past article&lt;/a&gt; might be more helpful in this case.&lt;br /&gt;&lt;br /&gt;Note 2: There is actually a number which has its sign bit set both normally and on negation, and that's the minimum-negative integer. With 32bit integers this number is -2147483648 (i.e. 0x80000000) (so with 32bit integers: 0x80000000 == -0x80000000).&lt;br /&gt;Using this knowledge, we now learned another neat trick. You can detect the minimum negative integer by doing: bool isMinNeg = x == -x; // x can be an int type of any size&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-562068034308434976?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/562068034308434976/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/10/0-or-1-bitwise-trick-int-to-boolean-int.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/562068034308434976'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/562068034308434976'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/10/0-or-1-bitwise-trick-int-to-boolean-int.html' title='Bitwise Set-Bit (#2)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4177664372935141007</id><published>2011-09-21T23:21:00.006-04:00</published><updated>2011-09-21T23:34:35.398-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>-1 or 1 bitwise trick</title><content type='html'>Been a while since my last update, and been a long time since my last bitwise trick.&lt;br /&gt;&lt;br /&gt;The Problem:&lt;br /&gt;If you have a 32bit signed integer, return -1 if the number is negative, and return 1 if the number is positive (or 0).&lt;br /&gt;&lt;br /&gt;The Typical Solution:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;s32 sign(s32 x) {&lt;br /&gt;    return x &lt; 0 ? -1 : 1;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The Bitwise Solution:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;s32 sign(s32 x) {&lt;br /&gt;    return (x&gt;&gt;31)|1;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;How does it work?&lt;br /&gt;Well (x&gt;&gt;31) does a signed shift with the sign bit, which will return either -1 if the sign bit was set (because -1 in binary is all 1's), or 0 if the sign bit wasn't set.&lt;br /&gt;But we want to return 1 when its positive; so what we do is OR the result with 1. (-1 | 1) == -1, and (0 | 1) == 1.&lt;br /&gt;So we get the result we wanted without needing a branch, and only using 2 very fast bitwise operations :D&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4177664372935141007?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4177664372935141007/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/09/1-or-1-bitwise-trick.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4177664372935141007'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4177664372935141007'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/09/1-or-1-bitwise-trick.html' title='-1 or 1 bitwise trick'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4359679299343456171</id><published>2011-06-01T18:23:00.003-04:00</published><updated>2011-06-01T19:19:47.892-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Don't initialize that big static data! (c++)</title><content type='html'>I learned this recently, and so I assume not a lot of people realize this.&lt;br /&gt;But lets take a look at some sample code:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;static const unsigned int _1mb = 1024*1024*1;&lt;br /&gt;char a[_1mb*10];&lt;br /&gt;int main() {}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;static const unsigned int _1mb = 1024*1024*1;&lt;br /&gt;char a[_1mb*10] = {7};&lt;br /&gt;int main() {}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now whats the difference between both of those programs? Well the only difference is that the bottom one is initializing a[0] to 7. Both of the programs initialize the rest of the a[n] data to 0.&lt;br /&gt;In the first one, all of 'a' gets initialized to 0 because all static/global data that is not explicitly initialized gets initialized to 0 (as per some rule in C).&lt;br /&gt;In the second one, the first element of 'a' gets initialized to 7 because we explicitly told it that in the array initializer and the rest of the data is filled with 0's because when you have an array initializer that does not cover all of the elements, the rest is treated as 0's.&lt;br /&gt;&lt;br /&gt;Now why do we care about this?&lt;br /&gt;Well why don't you try compiling both of those programs and take a look at the executable file?&lt;br /&gt;You might be surprised to find out that the first executable would be just a few kb, while the second would be over 10mb!&lt;br /&gt;&lt;br /&gt;Why is this?&lt;br /&gt;Well it turns out that compilers/linkers end up putting uninitialized static data in its own section called the &lt;a href="http://en.wikipedia.org/wiki/.bss"&gt;bss section&lt;/a&gt;. This section consists of data that is initialized to all 0's. This means that the executable doesn't need to store all that data in itself, it just needs information of how big the variable is, and where to place all the 0's in memory; it then does this when the application starts up.&lt;br /&gt;&lt;br /&gt;In contrast, the second example now explicitly initializes the data. Now the compiler/linker places that data in the data section, and it actually stores the full contents of the data in the executable. This means when you have an explicitly initialized 10mb chunk of data, your executable file will grow by 10mb!&lt;br /&gt;&lt;br /&gt;The exception to the above rule is data that is initialized to 0. Like if we had "char a[_1mb*10] = {0};", now what will happen?&lt;br /&gt;Well it turns out it can either be put in the bss section or the data section. Apparently some compiler/linkers might be stupid enough to put it into the data section meaning the executable will still grow by 10mb. Thankfully msvc isn't that stupid and it doesn't do that (the built executable is the same as if you didn't explicitly initialize 'a').&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Anyways, the moral of the story is to keep the above information in mind when you are explicitly initializing data.&lt;br /&gt;What would be a way to explicitly initialize a[0] to '7' at program startup w/o bloating the executable an extra 10mb?&lt;br /&gt;Well this is one way:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;static const unsigned int _1mb = 1024*1024*1;&lt;br /&gt;char a[_1mb*10];&lt;br /&gt;struct _init_a {&lt;br /&gt;    _init_a(char* c) { c[0] = 7; }&lt;br /&gt;}  __init_a(a);&lt;br /&gt;int main() {}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now __init_a's constructor will end up initializing a[0] to 7 at the application startup like we wanted. (Note: remember to beware of the &lt;a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14"&gt;static initializion order fiasco&lt;/a&gt; problem in c++ if you will have other static variable's constructors using 'a').&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4359679299343456171?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4359679299343456171/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/06/dont-initialize-that-big-static-data-c.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4359679299343456171'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4359679299343456171'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/06/dont-initialize-that-big-static-data-c.html' title='Don&apos;t initialize that big static data! (c++)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2467381943172283803</id><published>2011-05-26T05:16:00.004-04:00</published><updated>2011-05-26T05:46:44.843-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='comments'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Commenting Code</title><content type='html'>&lt;blockquote&gt;Meh...Most comments I've encountered in my life are written under the assumption that comments can make up for poorly written code.. – Stargazer712 Oct 14 '10 at 20:53&lt;/blockquote&gt;&lt;br /&gt;I saw the above comment on &lt;a href="http://programmers.stackexchange.com/questions/39/whats-your-favourite-quote-about-programming/53#53"&gt;this page&lt;/a&gt;, and I highly agree with what Stargazer712 said.&lt;br /&gt;&lt;br /&gt;So often I hear people talking about commenting code as a 'solution' to making crap code understandable. Using comments in this manner is not a solution, but instead a hacky work-around for the in-ability to produce quality code.&lt;br /&gt;&lt;br /&gt;If code is well written and structured, then the amount of comments you need can be greatly reduced, as the code itself would be pretty self explanatory.&lt;br /&gt;&lt;br /&gt;Furthermore comments can be misleading and do more harm than good. I've seen many cases where a comment says code does one thing, but its really doing another. Or I've seen bad coders change code, but leave in their old comments which are now totally irrelevant, just making the reader more confused.&lt;br /&gt;&lt;br /&gt;I'm not saying comments are bad, but I am saying that they are no excuse to be writing crap code. Sometimes code gets very complex, and its not due to the programmer being bad, but instead because they are heavily optimizing something or they are implementing something that's very involved and tricky. In these cases commenting code is very helpful and justified.&lt;br /&gt;&lt;br /&gt;Something I personally don't like to see is a lot of comments in the main .cpp files of a project, mainly because it gets in the way of code. Instead I like comments to be placed in the headers and next to the function prototypes away from the main implementation of the code so that when you are actually looking at the .cpp file, you can focus on the real code instead of seeing a wall of green-text getting in the way.&lt;br /&gt;If they're 1 or 2-liner comments then its fine to put them in the .cpp file, but if you're going to write a paragraph then save it for the .h file because I don't want to see that when I'm trying to understand your code (your real code, not what you 'say' your code does!).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Another thing I see often that newbie coders love to do is write obvious comments. Stuff like "i = 1; // set i to 1", these comments are not at all helpful, and they only serve to bloat code.&lt;br /&gt;&lt;br /&gt;Anyways I guess I can rant more, especially about bloated code, but I'll think I'll save that for a future post.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2467381943172283803?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2467381943172283803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/05/commenting-code.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2467381943172283803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2467381943172283803'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/05/commenting-code.html' title='Commenting Code'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-7459817339714340420</id><published>2011-05-11T19:48:00.002-04:00</published><updated>2011-05-22T09:01:36.213-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Checking if variables are of certainin type in C++</title><content type='html'>Okay this problem is something I often see people do incorrectly in c++.&lt;br /&gt;&lt;br /&gt;I've seen people use the sizeof() operator to try and distinguish types such as:&lt;br /&gt;&lt;pre class="brush: c++"&gt;template&amp;lt;typename T&amp;gt; void foo(T x) {&lt;br /&gt;    if (sizeof(x) == sizeof(string)) cout &lt;&lt; "x is a string\n";&lt;br /&gt;    if (sizeof(x) == sizeof(char))   cout &lt;&lt; "x is a char\n";&lt;br /&gt;    if (sizeof(x) == sizeof(int))    cout &lt;&lt; "x is a int\n";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above is obviously wrong because different types can have the same size. In many 32bit implementations sizeof(std::string) will be equal to sizeof(int).&lt;br /&gt;&lt;br /&gt;Now how can we do this better?&lt;br /&gt;Well there's a few ways to do this, one way can be to use template specialization for each of the above cases and make separate functions.&lt;br /&gt;&lt;br /&gt;But I'll explain another way. Boost has a templated struct called is_same which we can use in this case. However if you're like me and don't like using a lot of dependencies or over-engineered libraries in your code, then we can write our own code to tell us if two types are the same or not.&lt;br /&gt;It looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;template&amp;lt;typename A, typename B&amp;gt;&lt;br /&gt;struct _isSame { static const bool value = false; };&lt;br /&gt;template&amp;lt;typename A&amp;gt;&lt;br /&gt;struct _isSame&amp;lt;A, A&amp;gt; { static const bool value = true; };&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We can now use the above code like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;template&amp;lt;typename T&amp;gt; void foo(T x) {&lt;br /&gt;    if (_isSame&amp;lt;T, string&amp;gt;::value) cout &lt;&lt; "x is a string\n";&lt;br /&gt;    if (_isSame&amp;lt;T, char&amp;gt;::value)   cout &lt;&lt; "x is a char\n";&lt;br /&gt;    if (_isSame&amp;lt;T, int&amp;gt;::value)    cout &lt;&lt; "x is a int\n";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Lastly, we can make a helper function that lets us know if two variables are of the same type.&lt;br /&gt;&lt;pre class="brush: c++"&gt;template&amp;lt;typename A, typename B&amp;gt;&lt;br /&gt;inline bool isSame(A a, B b) { return _isSame&amp;lt;A, B&amp;gt;::value; }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And here's an example using the above function:&lt;br /&gt;&lt;pre class="brush: c++"&gt;int main() {&lt;br /&gt;    int x = 0;&lt;br /&gt;    int y = 0;&lt;br /&gt;    float z=0;&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; "Is x's type the same as y's type? ";&lt;br /&gt;    cout &lt;&lt; (isSame(x, y) ? "Yes" : "No") &lt;&lt; endl;&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; "Is x's type the same as z's type? ";&lt;br /&gt;    cout &lt;&lt; (isSame(x, z) ? "Yes" : "No") &lt;&lt; endl;&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-7459817339714340420?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/7459817339714340420/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/05/checking-if-type-is-same-as-another.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7459817339714340420'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7459817339714340420'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/05/checking-if-type-is-same-as-another.html' title='Checking if variables are of certainin type in C++'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5342912099046952358</id><published>2011-04-14T05:37:00.007-04:00</published><updated>2011-04-14T06:09:51.482-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>c++ functions returning void</title><content type='html'>I'm busy with exams now but I wanted to do a quick update on my blog after realizing how long its been since my last update &gt;&lt;&lt;br /&gt;&lt;br /&gt;Anyways this post is about something that isn't seen too-often in c++ so might not be known to some people; c++ void functions can return things, as long as the type is void.&lt;br /&gt;&lt;br /&gt;That means all of these are valid to do in c++:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo1 {}&lt;br /&gt;void foo2 { return; }&lt;br /&gt;void foo3 { return (void)0; }&lt;br /&gt;void foo4 { return (void)1.1; }&lt;br /&gt;void foo5 { return (void)(cout &lt;&lt; "hello world"); }&lt;br /&gt;void foo6 { return foo5(); }&lt;/pre&gt;&lt;br /&gt;You might think these are useless, but in some cases you might find it aesthetically pleasing to use one of the above styles in your code.&lt;br /&gt;&lt;br /&gt;For example, in an emulator you can have an opcode execute function for your interpreter that looks something like:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void opExecute {&lt;br /&gt;    unsigned char opcode = fetch();&lt;br /&gt;    switch(opcode) {&lt;br /&gt;        case 0x84: return ADD();&lt;br /&gt;        case 0x62: return SUB();&lt;br /&gt;        case 0x34: return BR();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In this case it looks aesthetically pleasing to be returning a void function.&lt;br /&gt;&lt;br /&gt;Another reason it might be useful is because it allows you to do in 1 statement what would otherwise take 2 statements.&lt;br /&gt;Consider this code:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo() {&lt;br /&gt;    if (cond) { cout &lt;&lt; "hello world"; return; }&lt;br /&gt;    //... do some code&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The above if-statement needs brackets around it because it's body has 2 statements in it. But if you cast to void you can combine both statements into one and not need the brackets like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo() {&lt;br /&gt;    if (cond) return (void)(cout &lt;&lt; "hello world");&lt;br /&gt;    //... do some code&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In terms of clarity and length, the first way was better; but sometimes there are situations where you want to keep things as 1 statement to prevent possible errors (like when you're creating macros), so knowing that you can do stuff like this might be useful.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5342912099046952358?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5342912099046952358/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/04/c-functions-returning-void.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5342912099046952358'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5342912099046952358'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/04/c-functions-returning-void.html' title='c++ functions returning void'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3079333031545988546</id><published>2011-01-29T22:12:00.005-05:00</published><updated>2011-01-29T22:33:36.758-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='emulation'/><category scheme='http://www.blogger.com/atom/ns#' term='NES'/><category scheme='http://www.blogger.com/atom/ns#' term='cottonNES'/><title type='text'>Porting cottonNES</title><content type='html'>Lately I've been working on porting cottonNES to arm based cell phones, using the Airplay SDK which lets me use C++ and compile native code on a variety of arm-based platforms (iOS phones, android phones, etc...).&lt;br /&gt;&lt;br /&gt;My original goal was to get cottonNES working on my iphone and I already accomplished that, but it turned out that a cycle accurate interpreted NES emulator on an iphone 3G runs very slow xD (about 5fps w/o frameskipping).&lt;br /&gt;&lt;br /&gt;This slowness just won't do, so I said, "hey now i finally have a reason to code a NES dynarec!" So i went to work studying the ARM instruction set and learned the instruction encodings to code an arm code-emitter (which lets me write arm code to memory buffers so that i can later execute the generated code).&lt;br /&gt;&lt;br /&gt;Well it turns out that the iOS on the iphone won't let me execute any code that was dynamically generated. I was using the Airplay SDK and mmap() to allocate a buffer with execution privileges, then emit arm code to it, then execute that buffer; but this ends up crashing on my jailbroken iphone 3G with firmware 3.1.2.&lt;br /&gt;&lt;br /&gt;So at that point I was disappointed, and pissed off at fucking apple with their shit iOS. But not all hope was lost since I could still just port my emulator to Android phones which DO let me execute dynamically generated code (and therefor allow the possibility of dynarecs/JIT compilers).&lt;br /&gt;&lt;br /&gt;The sad thing is i do not have an android phone to test my code on, but there are emulators i can use to test my code on the PC; and hopefully it will work on the real android phones.&lt;br /&gt;&lt;br /&gt;I already had someone try my test-app on a real android phone, which tests the ability to execute dynamically generated code. And they told me the app worked on their droid, so this is good news.&lt;br /&gt;&lt;br /&gt;If i don't get bored with the project, this should be the first nintendo emulator with a real dynarec ever AFAIK (there's one emulator i've seen claim to use dynamic recompilation, but it was really doing what i call "function caching", and not a real dynarec).&lt;br /&gt;&lt;br /&gt;Anyways, here's a pic of the interpreter version running on one of airplay's simulators:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_WwIahqE-1Co/TUTXjJoybDI/AAAAAAAAACk/iFM-lZSPXOU/s1600/cottonNES.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 200px;" src="http://1.bp.blogspot.com/_WwIahqE-1Co/TUTXjJoybDI/AAAAAAAAACk/iFM-lZSPXOU/s320/cottonNES.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5567812038219164722" /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3079333031545988546?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3079333031545988546/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/porting-cottonnes.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3079333031545988546'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3079333031545988546'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/porting-cottonnes.html' title='Porting cottonNES'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_WwIahqE-1Co/TUTXjJoybDI/AAAAAAAAACk/iFM-lZSPXOU/s72-c/cottonNES.png' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-8814292721319916105</id><published>2011-01-12T01:10:00.011-05:00</published><updated>2011-01-12T13:15:12.466-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Dynamically allocate aligned memory (aligned_malloc)</title><content type='html'>The other day on irc i noticed some dolphin-emu developers having a problem where they needed to guarantee 16-byte alignment on some dynamically allocated memory.&lt;br /&gt;&lt;br /&gt;You might be thinking: What does that mean? Why is this needed?&lt;br /&gt;Well if you've done any programming and dealt with pointers, you should know that the pointer holds a memory address location which is where the data its pointing to is stored.&lt;br /&gt;That memory address is just a number, and for it to be aligned to a 16-byte boundary means that the memory address needs to be a multiple of 16 (think of all of the computer's memory being divided into 16-byte chunks, what we want is the beginning of one of those chunks).&lt;br /&gt;&lt;br /&gt;The reason we want this is because there are some cpu instructions that require memory to be aligned to certain byte boundaries. Many SSE instructions require 16-byte alignment when reading from memory locations. SSE deals with xmm registers which hold 16 bytes of data each, so it's instructions like to work with addresses that are multiples of 16 (there are some SSE instructions that don't need alignment, but they're usually slower). If an SSE instruction that required alignment reads data that is un-aligned, your program will most-likely crash.&lt;br /&gt;&lt;br /&gt;So this was exactly the problem the dolphin-emu devs were having. They were using SSE instructions which required alignment, but reading data that was not guaranteed to be aligned. So the end result is it produced random crashes.&lt;br /&gt;&lt;br /&gt;So how do we solve this problem?&lt;br /&gt;&lt;br /&gt;Well there is an msvc function called &lt;a href="http://msdn.microsoft.com/en-us/library/8z34s9c6.aspx"&gt;_aligned_malloc&lt;/a&gt; which you can use to allocate memory aligned to whatever byte boundary you want (as long as its a power of 2).&lt;br /&gt;However _aligned_malloc is non-standard and other compilers like GCC won't have it (afaik).&lt;br /&gt;&lt;br /&gt;So what we want is a more portable solution that will work on all modern c/c++ compilers. How do we do this? We code our own!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Alignment must be power of 2 (1,2,4,8,16...)&lt;br /&gt;void* aligned_malloc(size_t size, size_t alignment) {&lt;br /&gt;    uintptr_t r = (uintptr_t)malloc(size + --alignment + sizeof(uintptr_t));&lt;br /&gt;    uintptr_t t = r + sizeof(uintptr_t);&lt;br /&gt;    uintptr_t o =(t + alignment) &amp; ~(uintptr_t)alignment;&lt;br /&gt;    if (!r) return NULL;&lt;br /&gt;    ((uintptr_t*)o)[-1] = r;&lt;br /&gt;    return (void*)o;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void aligned_free(void* p) {&lt;br /&gt;    if (!p) return;&lt;br /&gt;    free((void*)(((uintptr_t*)p)[-1]));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now my code above might scare you. But I'll try to explain what its doing.&lt;br /&gt;&lt;br /&gt;The first thing to note is how to use it. Basically you allocate an aligned chunk of memory with the aligned_malloc() function, then when you're done you free it with the aligned_free() function.&lt;br /&gt;So to allocate a 160 byte chunk of memory thats aligned to a 16-byte boundary, you can do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void* p = aligned_malloc(160, 16);&lt;br /&gt;... do something ...&lt;br /&gt;aligned_free(p);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now we get to the part of "fucking aligned_malloc, how does it work!?"&lt;br /&gt;The first thing to note is that when we allocate any chunk of memory and we want to align it to some byte boundary, there are N possible different positions that memory can be in terms of alignment (where N = alignment size)&lt;br /&gt;For example, if we want 4-byte alignment, and we do "void* p = malloc(10);", then the last 2 binary-digits of p are either 00,01,10,or 11. And if the last 2 digits are 00, that means that the memory is already aligned, that means that 1/4 times the memory is aligned already for us. 3/4 times the memory is not-aligned to 4-byte boundary (01,10,11). From this relationship we see that out of N different possibilities, N-1 outcomes will not be aligned.&lt;br /&gt;&lt;br /&gt;So to align data we just need to allocated "memory + N-1" amount of space, and offset the memory pointer to point to the first aligned chunk of memory.&lt;br /&gt;&lt;br /&gt;There is a trick to doing this, and it looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// p = address of a random chunk of memory&lt;br /&gt;// N = alignment we want; must be power of 2&lt;br /&gt;aligned_offset = (p + (N-1)) &amp; ~(N-1);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;With the above code, aligned_offset will equal the nearest aligned boundary. Try and analyze the code yourself to see how it works (note that N has to be a power of 2).&lt;br /&gt;&lt;br /&gt;Now that we know the above trick to get an aligned address from any arbitrary address, we now know the basis of aligned_malloc().&lt;br /&gt;&lt;br /&gt;The problem is that we can't just offset the pointer and then return that aligned address; because that means when it comes time to free() or delete[] the data, the pointer pointing to the data will not be correct.&lt;br /&gt;So to solve this problem we use another trick. We can allocate a bit more memory to store the starting address of real allocated memory. Then we place that address somewhere in the memory before the offset pointer we return.&lt;br /&gt;So it looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;| unused_data0 | start_address | aligned_data | unused_data1 |&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The pointer we're returning points to the beginning of aligned_data. But before that we have the start_address which points to the beginning of unused_data0 (the start of the allocated buffer).&lt;br /&gt;&lt;br /&gt;So with that info, you should be able to analyze aligned_malloc() line-by-line and understand what its doing. If you still don't understand leave a comment with what you're having trouble with.&lt;br /&gt;&lt;br /&gt;The last thing to look at is aligned_free. All we're doing when it comes time to free the allocated buffer, is we're grabbing the real start_address of the buffer which was placed immediately before our aligned data, and then freeing the memory where start_address points to.&lt;br /&gt;&lt;br /&gt;Again if there's any questions feel free to comment. Hopefully my explanation made sense.&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;In the above functions we're using malloc to allocate the memory. We could instead use c++'s 'new[]' operator to allocate the chunk of memory and 'delete[]' to free it. The reason we didn't is because 'new[]' is c++ only, by using malloc the code works with both c and c++. If you don't care about c-compatibility then you can easily convert the function to use new[]/delete[].&lt;br /&gt;&lt;br /&gt;Another thing to note is that the above aligned_malloc is storing the full address of the buffer's starting address. If you limit the alignment max to be 2^15 or less, then you can instead store the difference between the returned offset and the start of the buffer which would only take 2-bytes of extra-storage (instead of sizeof(uintptr_t), which is 4-bytes on 32bit os, and 8-bytes on 64-bit os)&lt;br /&gt;&lt;br /&gt;Here is what the code looks like for the space-saving version:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Alignment must be power of 2 (1,2,4,8,16...2^15)&lt;br /&gt;void* aligned_malloc(size_t size, size_t alignment) {&lt;br /&gt;    assert(alignment &lt;= 0x8000);&lt;br /&gt;    uintptr_t r = (uintptr_t)malloc(size + --alignment + 2);&lt;br /&gt;    uintptr_t o = (r + 2 + alignment) &amp; ~(uintptr_t)alignment;&lt;br /&gt;    if (!r) return NULL;&lt;br /&gt;    ((uint16_t*)o)[-1] = (uint16_t)(o-r);&lt;br /&gt;    return (void*)o;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void aligned_free(void* p) {&lt;br /&gt;    if (!p) return;&lt;br /&gt;    free((void*)((uintptr_t)p-((uint16_t*)p)[-1]));&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-8814292721319916105?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/8814292721319916105/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/dynamically-allocate-aligned-memory.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8814292721319916105'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8814292721319916105'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/dynamically-allocate-aligned-memory.html' title='Dynamically allocate aligned memory (aligned_malloc)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3471140160931708951</id><published>2011-01-06T01:36:00.004-05:00</published><updated>2011-01-06T03:23:03.902-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='static'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Using and understanding the static keyword C++, as well as some interesting tricks</title><content type='html'>There are just so many things I can talk about here, so its difficult to condense this into a small blog post. I would like to rant about how I hate c++'s header/.cpp translation unit model mess, but I won't in order to keep this shorter.&lt;br /&gt;&lt;br /&gt;The first thing to mention is that when you compile a c++ project with multiple .cpp files, what essentially happens is all the .h files included in the .cpp files are expanded and merged with the .cpp file to form a translation unit which the compiler uses to generate an object file. The different translation units don't know about the other .cpp files, so that's why you need function and class prototypes and extern-variables (such as 'extern int;') which tell the compiler/linker that these functions/classes/variables exist in some .cpp file. (This crappy design is the worst thing about c++, and it was inherited from the c programming language, most-likely so that the compiler can save memory when compiling your source code. Newer more advanced languages like c# don't need header files because their compilers are smart enough to detect the different functions/classes/variables in separate files without prototypes).&lt;br /&gt;&lt;br /&gt;So because of the above design, we need to use crappy header files in our large c++ projects. There are some tricks I've learned over the years to eliminate the need for many duplicate prototype/declaration/definition mess, although it is not commonly used by other c++ coders and they probably won't like the tricks because its not the common way to program. That said I will probably talk more in detail about this in another article.&lt;br /&gt;&lt;br /&gt;Now why is the static keyword useful? Well c++ being the evil bastard that it is, has different meanings for the static keyword depending on how its used. So just talking about 'static' in general is not specific enough.&lt;br /&gt;&lt;br /&gt;One use of static is in the file-scope. This tells the compiler that the variable/function is unique to the current translation unit (.cpp file) not visible to other .cpp files.&lt;br /&gt;&lt;br /&gt;So if you have:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;static int x = 10;&lt;br /&gt;int main() { cout &lt;&lt; x &lt;&lt; endl; return 0; }&lt;br /&gt;// source2.cpp&lt;br /&gt;extern int x;&lt;br /&gt;int foo() { x++; }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above code will give you a linker error after compiling:&lt;br /&gt;source2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA)&lt;br /&gt;&lt;br /&gt;If you remove the static keyword, then it will compile. The reason is as mentioned before, static will make the variable unique to the translation unit essentially hiding it from other units.&lt;br /&gt;&lt;br /&gt;The properties of a static variables declared at global file scope (not in a function) are that they're initiated at the start of the program, and then they're deconstructed at the end of the program.&lt;br /&gt;So if you were to have a line of code that said "static someClass myClass(10);" and it was in global file scope, then the constructor myClass will be called sometime before the main() function in your program, and its destructor gets called when exiting your program.&lt;br /&gt;&lt;br /&gt;One misleading thing c++ does is it changes this behavior when you have nested static variables in function scope.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int foo() { &lt;br /&gt;    static someClass myClass(10);&lt;br /&gt;    return myClass.someFunct();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now you might expect myClass's constructor to be called at the beginning of the program, but this is not the case. Instead the constructor is called the first time the foo() function is ever called! This is a tricky part of the standard that may cause confusion at first.&lt;br /&gt;&lt;br /&gt;The interesting thing about this behavior is that although its tricky and seemingly evil, it also is useful. Specifically it allows us to know the time of initialization of the static nested variables. When static variables are initialized in global file scope, it is unknown which order they get initialized in (relative to other static variables, and this is one reason people think they're evil; because they can be initialized before data they depend on is initialized). Using nested static variables eliminates this problem because we &lt;span style="font-weight:bold;"&gt;know&lt;/span&gt; that the first time we're calling function foo(), the constructor of the static variable is called.&lt;br /&gt;&lt;br /&gt;Now to take advantage of this we can declare static variables like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Instead of doing this:&lt;br /&gt;// static someClass myClass(10);&lt;br /&gt;&lt;br /&gt;// We do this:&lt;br /&gt;someClass&amp; myClass() { &lt;br /&gt;    static someClass _myClass(10);&lt;br /&gt;    return _myClass;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now we can use 'myClass()' and we know that the first time its called will be when the constructor is called.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now moving on, we can have static functions as well.&lt;br /&gt;Static functions behave like static variables at file scope because it creates a unique function for the .cpp file where its defined, and its hidden from the other .cpp files.&lt;br /&gt;You might think it doesn't matter, and it doesn't for the most part, but imagine the following code:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// header.h&lt;br /&gt;static int&amp; getInt() {&lt;br /&gt;    static int i = 77;&lt;br /&gt;    return i;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo();&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    foo();&lt;br /&gt;    cout &lt;&lt; getInt() &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// source2.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo() {&lt;br /&gt;    getInt() = 10;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;What do you think the output of the program will be?&lt;br /&gt;You might think the output should be 10, but its not, its 77.&lt;br /&gt;&lt;br /&gt;The reason for this is that we declared the function getInt() as static, that means for both source1.cpp and source2.cpp, it created separate local versions of the getInt() function. So when getInt() is called in source2.cpp's foo(), it is a separate function than getInt() the one source1.cpp sees, so when source1.cpp prints out getInt() it prints its own version which was initialized to 77.&lt;br /&gt;&lt;br /&gt;What happens if we remove the 'static' keyword from 'static int&amp; getInt()', well we get linker errors:&lt;br /&gt;1&gt;source1.obj : error LNK2005: "int &amp; __cdecl getInt(void)" (?getInt@@YAAAHXZ) already defined in source2.obj&lt;br /&gt;&lt;br /&gt;This is because the function is trying to be defined in both .cpp files so the linker doesn't know which version to use.&lt;br /&gt;The usual way to prevent these problems is to define the function in one .cpp file, and then have the function prototype in the header like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// header.h&lt;br /&gt;int&amp; getInt();&lt;br /&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo();&lt;br /&gt;&lt;br /&gt;int&amp; getInt() {&lt;br /&gt;    static int i = 77;&lt;br /&gt;    return i;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    foo();&lt;br /&gt;    cout &lt;&lt; getInt() &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// source2.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo() {&lt;br /&gt;    getInt() = 10;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The program now prints what you expect it to print, "10".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now that we got that out of the way, we can talk about the static keyword in classes and structs.&lt;br /&gt;&lt;br /&gt;When you have a struct/class with a static member variable, you're required to declare it in the struct, but then define it outside the struct.&lt;br /&gt;So you do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// header.h&lt;br /&gt;struct someStruct {&lt;br /&gt;    static int i; // declare&lt;br /&gt;    // static int i = 10; // c++ doesn't allow this&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;&lt;br /&gt;// This line must go in only 1 translation unit&lt;br /&gt;// so it should only be put in one .cpp file&lt;br /&gt;int someStruct::i = 10; // define i&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There will now be only 1 instance of someStruct::i, and you can use it throughout your code such as 'someStruct::i = 49'.&lt;br /&gt;&lt;br /&gt;If you noticed though c++ makes you split the definition of the variable from the declaration; and the definition is put into only 1 .cpp file.&lt;br /&gt;Well there is workaround for this which lets you define it in the same place you declare it.&lt;br /&gt;&lt;br /&gt;Before I mention the solution, I'll mention another problem with c++.&lt;br /&gt;What if you wanted to do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;struct someStruct {&lt;br /&gt;    static const int i = 24; // This compiles&lt;br /&gt;    static const char* message = "Hello world"; // This doesn't&lt;br /&gt;    void foo() { cout &lt;&lt; message &lt;&lt; " " &lt;&lt; i &lt;&lt; endl; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The only thing c++ allows us to initialize within a class are "static const int" variables, anything else it requires you to split the initialization part into a .cpp file.&lt;br /&gt;&lt;br /&gt;Now whats the solution?&lt;br /&gt;static member functions with static local variables!&lt;br /&gt;&lt;br /&gt;Here's cool way to fix the problem:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;struct someStruct {&lt;br /&gt;    static const int i = 24;&lt;br /&gt;    static const char* message() {&lt;br /&gt;        static const char* _message = "Hello world";&lt;br /&gt;        return _message;&lt;br /&gt;    }&lt;br /&gt;    void foo() { cout &lt;&lt; message() &lt;&lt; " " &lt;&lt; i &lt;&lt; endl; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The evil part about c++ is that static member functions with static local variables behave differently than static file-scope functions with static local variables.&lt;br /&gt;&lt;br /&gt;This example will illustrate that:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// header.h&lt;br /&gt;static int&amp; getInt() {&lt;br /&gt;    static int i = 77;&lt;br /&gt;    return i;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;struct someStruct {&lt;br /&gt;    static int&amp; getInt() {&lt;br /&gt;        static int i = 77;&lt;br /&gt;        return i;&lt;br /&gt;    } &lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo();&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    foo();&lt;br /&gt;    cout &lt;&lt; getInt() &lt;&lt; endl;&lt;br /&gt;    cout &lt;&lt; someStruct::getInt() &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// source2.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo() {&lt;br /&gt;    getInt() = 10;&lt;br /&gt;    someStruct::getInt() = 10;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;What do you think the output of the program will be?&lt;br /&gt;Well the first cout with the file-scope function we know will print '77', because this is the same example i gave earlier in this article. But strangely the second line with 'someStruct::getInt()' returns 10!&lt;br /&gt;&lt;br /&gt;The reason for this is that static local variables in class member functions will only have 1 instance of themselves, even throughout different translation units!&lt;br /&gt;&lt;br /&gt;This is a powerful thing to know and can be used for random tricks.&lt;br /&gt;&lt;br /&gt;This last example i'm going to give will show you a trick so that you can declare and define static variables in a header file that are used in different .cpp files, but the variable will be the same throughout all the different translation units (so it doesn't make unique copies like normal static at file-scope does).&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// header.h&lt;br /&gt;struct someStruct {&lt;br /&gt;    static int&amp; getInt() {&lt;br /&gt;        static int i = 77;&lt;br /&gt;        return i;&lt;br /&gt;    } &lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;static int&amp; i = someStruct::getInt();&lt;br /&gt;&lt;br /&gt;// source1.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo();&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    foo();&lt;br /&gt;    cout &lt;&lt; i &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// source2.cpp&lt;br /&gt;#include "header.h"&lt;br /&gt;void foo() {&lt;br /&gt;    i = 10;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The above code prints out 10.&lt;br /&gt;Notice how we didn't have to declare any variable in the individual .cpp files and could declare and initialize the variables all in the header file.&lt;br /&gt;This trick can be useful, so use it wisely.&lt;br /&gt;&lt;br /&gt;Hope this article was useful for at least someone :p&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3471140160931708951?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3471140160931708951/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/using-and-understanding-static-keyword.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3471140160931708951'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3471140160931708951'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2011/01/using-and-understanding-static-keyword.html' title='Using and understanding the static keyword C++, as well as some interesting tricks'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-7660030752868795307</id><published>2010-12-24T02:02:00.013-05:00</published><updated>2011-01-06T00:54:19.177-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Append integer to string (c++)</title><content type='html'>In this blog article we'll be using operator overloading with strings to let us append integers to the end of them (something pretty useful which std::string doesn't do for us already! :/)&lt;br /&gt;&lt;br /&gt;We will be using some code described in a &lt;a href="http://cottonvibes.blogspot.com/2010/10/easy-generic-tostring-function-in-c.html"&gt;previous article&lt;/a&gt; to do the actual conversion from int to string.&lt;br /&gt;&lt;br /&gt;We will be overloading the "&lt;&lt;" operator so that we can append to a string, and we will use the "+" operator so that we return a copy of the result of appending a string.&lt;br /&gt;&lt;br /&gt;So it will work as follows:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    string str0("hello");&lt;br /&gt;    string str1("hello");&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; str0 &lt;&lt; endl; // prints 'hello'&lt;br /&gt;    str0 &lt;&lt; 123;&lt;br /&gt;    cout &lt;&lt; str0 &lt;&lt; endl; // prints 'hello123'&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; str1 &lt;&lt; endl; // prints 'hello'&lt;br /&gt;    str1 + 123; // does not modify str1 (effectively does nothing)&lt;br /&gt;    cout &lt;&lt; str1 &lt;&lt; endl; // prints 'hello'&lt;br /&gt;    cout &lt;&lt; str1 + 123 &lt;&lt; endl; // prints 'hello123'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Note: The reason we're overloading '&lt;&lt;' instead of '+=', is because '+=' is not an operator that allows for global operator overloading. See &lt;a href="http://www.cplusplus.com/doc/tutorial/classes2/"&gt;this link&lt;/a&gt; for more details on that.&lt;br /&gt;&lt;br /&gt;So how do we make the above code work?&lt;br /&gt;We need to add the following above the 'main()' function:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;string toString(T t) {&lt;br /&gt;    stringstream s;&lt;br /&gt;    s &lt;&lt; t;&lt;br /&gt;    return s.str();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;string&amp; operator&lt;&lt;(string&amp; s, int i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;string operator+(string s, int i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Using the above overloads, the code in the main() function compiles and prints what we wanted it to.&lt;br /&gt;&lt;br /&gt;Notice that the '&lt;&lt;' operator overload takes a reference to a string as one of its parameters, this is done so that the actual string is modified. The '+' operator overload takes a copy of the string and then does the appending, so the original string is not modified.&lt;br /&gt;&lt;br /&gt;We can extend the above code to work for floats, doubles, and any datatype that our toString() function accepts. One way we do that is to use templates on our operator overloads.&lt;br /&gt;&lt;br /&gt;Here's the new code:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;string&amp; operator&lt;&lt;(string&amp; s, T i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;string operator+(string s, T i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Although the above code works and is cool, there is a downside to doing this.&lt;br /&gt;It won't allow us to do stuff like: string("s") + "hello", anymore. If we try to do that the compiler will generate a ambiguity error because it doesn't know which overload to choose. The +(string, char) overload is already defined by standard strings and our above template operator overload also handles this case; so the compiler doesn't know which to use and generates an error.&lt;br /&gt;&lt;br /&gt;Our solution then is to not use templates and just manually overload the operators for the specific types on the + operator, but to use templates for the &lt;&lt; operator since the c++ standard doesn't overload the &lt;&lt;(string, char) operator.&lt;br /&gt;This is the code I currently use in my projects:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;string&amp; operator&lt;&lt;(string&amp; s, T i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;br /&gt;string operator+(string s, int i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;br /&gt;string operator+(string s, float i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;br /&gt;string operator+(string s, double i) {&lt;br /&gt;    return s.append(toString(i));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So there you have it, you can now do stuff like:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;double myDouble = 123.79;&lt;br /&gt;string s("My double is ");&lt;br /&gt;s &lt;&lt; myDouble &lt;&lt; ". My int is " &lt;&lt; 12 &lt;&lt; ".";&lt;br /&gt;cout &lt;&lt; s &lt;&lt; endl; // prints 'My double is 123.79. My int is 12.'&lt;br /&gt;&lt;br /&gt;// this prints the same thing as above but uses &lt;br /&gt;// printf() and C-style strings (null-terminated char arrays)&lt;br /&gt;printf("%s", s.c_str());&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-7660030752868795307?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/7660030752868795307/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/append-integer-to-string-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7660030752868795307'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7660030752868795307'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/append-integer-to-string-c.html' title='Append integer to string (c++)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-7073981944743650577</id><published>2010-12-24T01:19:00.006-05:00</published><updated>2010-12-24T02:12:51.006-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='references'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='arrays'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Returning Arrays by Reference in C++</title><content type='html'>&lt;a href="http://cottonvibes.blogspot.com/2010/12/returning-arrays-and-multi-dimensional.html"&gt;Last article&lt;/a&gt; we talked about returning arrays, but we only did it by value (so that a copy of the data is returned). This time we'll look at returning arrays using references.&lt;br /&gt;&lt;br /&gt;This feature is something that I rarely see used in practice, I think partially because the syntax is so bizarre and confusing to those that have never seen it. I first saw it in some code by shuffle2 and thought it was crazy; but now I understand why the syntax is the way it is.&lt;br /&gt;&lt;br /&gt;Here's how to do it:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int testArr[5] = { 1000, 1, 2, 3, 4 };&lt;br /&gt;&lt;br /&gt;int (&amp;retArr())[5] {&lt;br /&gt;    return testArr;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int (&amp;arr)[5] = retArr();&lt;br /&gt;    cout &lt;&lt; arr[0] &lt;&lt; endl; // prints 1000&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The 'retArr()' is the function which is returning a reference to an int array with 5 elements. If you wanted any parameters for the function 'retArr()' you can place them in the '()' like you normally would.&lt;br /&gt;&lt;br /&gt;The seemingly awkward syntax becomes less awkward when you think of the syntax for declaring references to an array.&lt;br /&gt;'int (&amp;arr)[5] = ...' is how you would declare a normal reference to an array, so studying that syntax and then looking at the function prototype 'int (&amp;retArr())[5]' should help you understand it.&lt;br /&gt;&lt;br /&gt;Also why is returning a reference to an array useful?&lt;br /&gt;Well its useful for various reasons, but I'll give an interesting example.&lt;br /&gt;&lt;br /&gt;Assume that you have a memory buffer that was dynamically allocated (for w/e reason, maybe a custom allocation routine to guarantee alignment), then you want that buffer to be thought of as a fixed-size array; well you can do that by returning a reference to an array.&lt;br /&gt;&lt;br /&gt;Like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;struct myStruct {&lt;br /&gt;    int* myPtr;&lt;br /&gt;    myStruct() {&lt;br /&gt;        myPtr = new int[5];&lt;br /&gt;        myPtr[0] = 1000;&lt;br /&gt;        myPtr[1] = 1;&lt;br /&gt;        myPtr[2] = 2;&lt;br /&gt;        myPtr[3] = 3;&lt;br /&gt;        myPtr[4] = 4;&lt;br /&gt;    }&lt;br /&gt;    ~myStruct() {&lt;br /&gt;        delete[] myPtr;&lt;br /&gt;    }&lt;br /&gt;    int (&amp;getArray())[5] {&lt;br /&gt;        return (int(&amp;)[5])*myPtr; // cast to a reference&lt;br /&gt;    }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    myStruct testStruct;&lt;br /&gt;    cout  &lt;&lt; testStruct.getArray()[0] &lt;&lt; endl; // prints 1000&lt;br /&gt;    cout  &lt;&lt; sizeof(testStruct.getArray()) &lt;&lt; endl; // prints 20&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The benefit of returning an array by reference instead of just an int pointer in the above code is that the former explicitly tells the programmer reading the function signature that the buffer being returned holds 5 ints, returning an int pointer instead will not tell us how much elements are in the array.&lt;br /&gt;Also sizeof(testStruct.getArray()) returns 5*sizeof(int), whereas if we were returning an int pointer, it would just return sizeof(int*), which most-likely isn't what we wanted.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-7073981944743650577?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/7073981944743650577/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/returning-arrays-by-reference-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7073981944743650577'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7073981944743650577'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/returning-arrays-by-reference-in-c.html' title='Returning Arrays by Reference in C++'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3070608123018059298</id><published>2010-12-19T01:11:00.005-05:00</published><updated>2010-12-19T03:14:15.650-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='arrays'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Returning arrays in C++ (including multi-dimensional arrays)</title><content type='html'>&lt;a href="http://cottonvibes.blogspot.com/2010/12/passing-arrays-as-arguments-in-c.html"&gt;Last article&lt;/a&gt; we were talking about passing arrays as arguments and it got a bit long, so this time I'm going to try to keep it shorter.&lt;br /&gt;&lt;br /&gt;First I'll say that like when we passed an array by value in the last article, there is no built in easy way to return arrays by value, so we have to use workarounds.&lt;br /&gt;&lt;br /&gt;The first thing I'll show is some WRONG CODE that beginners might try to use:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int* getArray() {&lt;br /&gt;    int my_arr[10] = { 0,1,2,3,4,5,6,7,8,9 };&lt;br /&gt;    return my_arr;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int* arr = getArray();&lt;br /&gt;    arr[1] = 4;&lt;br /&gt;    for(int i = 0; i &lt; 10; i++) {&lt;br /&gt;        cout &lt;&lt; arr[i] &lt;&lt; endl;&lt;br /&gt;    }&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Can you see the error?&lt;br /&gt;Well the problem is that in the function getArray() the array 'my_arr' is being allocated on the stack, and then you are returning a pointer to it. By the time you're back in the function main() 'my_arr' is not guaranteed to be valid anymore so using it as if its valid will cause undefined behavior. So don't do this.&lt;br /&gt;&lt;br /&gt;Now lets look at some correct ways to do this.&lt;br /&gt;One way is to use dynamic memory allocation to allocate the array on the heap and then pass a pointer to it, and then consider that memory as an array.&lt;br /&gt;&lt;br /&gt;It looks like this (also note that I'm going to use a multi-dimensional array so people know how to do this):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;const int n = 5;&lt;br /&gt;const int m = 5;&lt;br /&gt;&lt;br /&gt;int* getArray() {&lt;br /&gt;    int* arr = new int[n*m];&lt;br /&gt;    for(int i = 0; i &lt; n*m; i++) arr[i] = i;&lt;br /&gt;    return arr;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int* ptr = getArray();&lt;br /&gt;    int (&amp;arr)[n][m] = (int(&amp;)[n][m])*ptr;&lt;br /&gt;    for(int i = 0; i &lt; n; i++) {&lt;br /&gt;    for(int j = 0; j &lt; m; j++) {&lt;br /&gt;        cout &lt;&lt; arr[i][j] &lt;&lt; endl;&lt;br /&gt;    }}&lt;br /&gt;    delete[] ptr;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In the function getArray() we allocate a chunk of memory the size of n*m*sizeof(int) bytes. Then we initialize it to the numbers 0...n*m-1, then we return it as an int*.&lt;br /&gt;Back in the function main() we get the ptr and then consider it as a multi-dimensional array by using references. Here you can see how to cast a pointer to an array (for single-dimensional arrays just ignore the extra [m] part).&lt;br /&gt;Lastly we need to remember to delete[] the ptr, because we allocated this memory on the heap so it won't automatically delete it for us.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Since the above method has us needing to delete[] our memory ourselves, it is slightly inconvenient. This last approach doesn't have that problem, we use a struct like we did when we passed arrays as arguments in the last article.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;const int n = 5;&lt;br /&gt;const int m = 5;&lt;br /&gt;&lt;br /&gt;struct arrayStruct {&lt;br /&gt;    int arr[n][m];&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;arrayStruct getArray() {&lt;br /&gt;    arrayStruct t;&lt;br /&gt;    for(int i = 0; i &lt; n; i++) {&lt;br /&gt;    for(int j = 0; j &lt; m; j++) {&lt;br /&gt;        t.arr[i][j] = i*m + j;&lt;br /&gt;    }}&lt;br /&gt;    return t;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    arrayStruct a = getArray();&lt;br /&gt;    for(int i = 0; i &lt; n; i++) {&lt;br /&gt;    for(int j = 0; j &lt; m; j++) {&lt;br /&gt;        cout &lt;&lt; a.arr[i][j] &lt;&lt; endl;&lt;br /&gt;    }}&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;When we use a struct to encapsulate the array, c++ creates a default copy constructor that will copy our data created in getArray() to our 'a' struct in main().&lt;br /&gt;&lt;br /&gt;If we didn't want to access the array by using 'a.arr[i][j]', we could again use references like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    arrayStruct a = getArray();&lt;br /&gt;    int (&amp;arr)[n][m] = a.arr;&lt;br /&gt;    for(int i = 0; i &lt; n; i++) {&lt;br /&gt;    for(int j = 0; j &lt; m; j++) {&lt;br /&gt;        cout &lt;&lt; arr[i][j] &lt;&lt; endl;&lt;br /&gt;    }}&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We have now seen a couple ways to do this, there are more ways to accomplish this task but this blog post would get huge if I continue listing the various ways.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3070608123018059298?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3070608123018059298/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/returning-arrays-and-multi-dimensional.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3070608123018059298'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3070608123018059298'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/returning-arrays-and-multi-dimensional.html' title='Returning arrays in C++ (including multi-dimensional arrays)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-1009132459266969755</id><published>2010-12-04T06:14:00.006-05:00</published><updated>2010-12-04T08:11:52.465-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='arrays'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Passing Arrays as Arguments in C++</title><content type='html'>In C++ and other programming languages there is the concept of Arrays.&lt;br /&gt;One of the things you might want to do with arrays is pass them to another function so that that function can read the data in the array.&lt;br /&gt;&lt;br /&gt;The simplest thing you might think of to accomplish this task might be:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo(char* a) {&lt;br /&gt;    cout &lt;&lt; a[0] &lt;&lt; endl; // prints 0&lt;br /&gt;    cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 4&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    char my_array[128] = {0};&lt;br /&gt;    foo(my_array);&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And this does work. What its doing here is passing the pointer to first element in 'my_array' to the function 'foo', and 'foo' uses it as a normal char*.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The problem with this approach is if you want to specify that you want an array of a certain size as the parameter to the function. Since we're treating the array as a pointer, there is no hint to the programmer of the size needed for the array.&lt;br /&gt;&lt;br /&gt;There is a feature that originated in C which lets us specify a size parameter, and it looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo(char a[128]) {&lt;br /&gt;    cout &lt;&lt; a[0] &lt;&lt; endl; // prints 0&lt;br /&gt;    cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 4&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    char my_array[128] = {0};&lt;br /&gt;    foo(my_array);&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now this method is pretty evil in C++ (although in C I guess its more justifiable since it doesn't support the better way which i will explain later).&lt;br /&gt;&lt;br /&gt;Now in the function 'foo' you are hinting to the programmer that you want an array with 128 elements, but guess what happens if you give it an array of 10 elements?&lt;br /&gt;Nothing happens, its perfectly fine accepting that.&lt;br /&gt;&lt;br /&gt;What happens if you pass it char* instead of an array of char?&lt;br /&gt;Nothing happens, its perfectly fine accepting that.&lt;br /&gt;&lt;br /&gt;Also notice what this function prints out. It prints out '4' for sizeof(a)!?&lt;br /&gt;&lt;br /&gt;Any experienced coder will know that sizeof(some_array) will be the size of one element times the number of elements. So why is it giving us '4' instead of '128'?&lt;br /&gt;&lt;br /&gt;Well it turns out that this feature is equivalent to the first method we used, that is it is as if we're passing a "char*", not an array by reference (as we may have thought).&lt;br /&gt;&lt;br /&gt;So once we realize that, it all makes sense, sizeof(char*) on a 32bit system is '4', so that's how we got that number.&lt;br /&gt;&lt;br /&gt;For these reasons this approach is what I would call 'evil'. You would expect it to behave a certain way, but it doesn't.&lt;br /&gt;&lt;br /&gt;There is a special form of the above C-feature that looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo(char a[]) {&lt;br /&gt;    cout &lt;&lt; a[0] &lt;&lt; endl; // prints 0&lt;br /&gt;    cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 4&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    char my_array[128] = {0};&lt;br /&gt;    foo(my_array);&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This time in the function 'foo' we didn't specify a size of the array.&lt;br /&gt;I don't think there's any reason to use this form as opposed to 'char* a' since they both behave the exact same way. And this time you're not even hinting to the programmer how big you want the array, so its kind-of pointless to have this notation.&lt;br /&gt;'char a[]' might look cool though compared to just using 'char* a', so maybe that's why someone might want to use it. Although i would just recommend using 'char* a' since its more commonly seen (and therefor easier to read imo).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now that we learned all these bad ways to pass arrays in C++, lets look at a good way.&lt;br /&gt;Passing an array by reference! (Before we were just using different forms of passing a char*, but this time we will pass the array by reference and the compiler will understand that it is array).&lt;br /&gt;&lt;br /&gt;It looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void foo(char (&amp;a)[128]) {&lt;br /&gt;    cout &lt;&lt; a[0] &lt;&lt; endl; // prints 0&lt;br /&gt;    cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 128&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    char my_array[128] = {0};&lt;br /&gt;    foo(my_array);&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Aha! Finally the sizeof(a) is printing out 128 (what we expected it to).&lt;br /&gt;Now 'a' is behaving like an array instead of 'char*' and that is what we wanted.&lt;br /&gt;&lt;br /&gt;Now guess what happens if we try to pass an array of 10 elements to function 'foo'?&lt;br /&gt;We get a compiler error! The compiler knows that an array of 10 elements is not an array of 128 elements, so it gives us an error.&lt;br /&gt;&lt;br /&gt;Now guess what happens if we try to pass a char* to the function 'foo'?&lt;br /&gt;We get a compiler error! The compiler knows that a char* is not the same as an array of 128 elements, so it gives use an error.&lt;br /&gt;&lt;br /&gt;The compiler errors are useful in order to prevent bugs by people who mistakenly are passing arrays of incorrect size to the function.&lt;br /&gt;In another article I will explain ways to circumvent such compiler errors when you 'know' for sure that the pointer/array you're passing is suitable for the function 'foo' but may not have the same type (such as an array of 1000 elements, whereas the function foo will only accept an array of 128 elements).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;We have learned how to pass arrays using pointers and references (which means that any data of the array 'a' that was modified in function 'foo' modifies the data in 'my_array'), now we will learn how to pass an array by value (which means that a copy of the array data will be transferred via the stack to function 'foo', so that modifications to 'a' will not effect 'my_array').&lt;br /&gt;&lt;br /&gt;Now here's the funny part about this, you can't do it! At least there's no fancy parameter declaration that lets you do this.&lt;br /&gt;&lt;br /&gt;There are various workarounds for this problem, and one of them is to create a struct which will act as the array, and then pass the array as that struct on the stack.&lt;br /&gt;&lt;br /&gt;For example:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;struct temp_struct {&lt;br /&gt;    char a[128];&lt;br /&gt;};&lt;br /&gt;C_ASSERT(sizeof(temp_struct)==sizeof(char)*128);&lt;br /&gt;&lt;br /&gt;void foo(temp_struct t) {&lt;br /&gt;    char (&amp;a)[128] = t.a; // reference to the array t.a&lt;br /&gt;    cout &lt;&lt; a[0] &lt;&lt; endl; // prints 0&lt;br /&gt;    cout &lt;&lt; sizeof(a) &lt;&lt; endl; // prints 128&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    char my_array[128] = {0};&lt;br /&gt;    foo((temp_struct&amp;)my_array);&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice what we did here. We created a struct 'temp_struct' which holds only a single array of the size we're passing. (I will explain what the C_ASSERT does in a bit).&lt;br /&gt;Then we made foo() take as a parameter the 'temp_struct' that we defined earlier.&lt;br /&gt;&lt;br /&gt;In the first line of foo's body, we create a reference to the first element inside the foo struct. Then we use this array reference like normally.&lt;br /&gt;&lt;br /&gt;Back in the function main(), we need to typecase my_array as a reference of type temp_struct. Basically what we're saying to the compiler is that this array should be treated as if it were a temp_struct, without doing any conversion of the data.&lt;br /&gt;Now the last thing is, since the compiler thinks my_array is a temp_struct, it will copy over the array on the stack (like it would do for any other struct that was passed by value). So with that we have completed our goal.&lt;br /&gt;&lt;br /&gt;C_ASSERT is a compile-time assert, and is useful for things like making sure structs you've declared are the size you expected them to be.&lt;br /&gt;The C_ASSERT in the above example is added just to make sure the compiler is generating the struct the same exact size as the array we're dealing with.&lt;br /&gt;If the compiler didn't make the struct the same size, then we would get a compiler error.&lt;br /&gt;I think that a compiler will never end up breaking that C_ASSERT. But I don't know the full c++ standard well enough to guarantee that will never happen, so that's why I add the check in the first place.&lt;br /&gt;&lt;br /&gt;Anyways hopefully this article was informative, and by now you should know how to pass an array by treating it as pointer, pass an array by reference, and pass an array by value.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-1009132459266969755?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/1009132459266969755/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/passing-arrays-as-arguments-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1009132459266969755'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1009132459266969755'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/passing-arrays-as-arguments-in-c.html' title='Passing Arrays as Arguments in C++'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4716010487178315883</id><published>2010-12-02T06:10:00.006-05:00</published><updated>2010-12-02T19:56:17.034-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='games'/><category scheme='http://www.blogger.com/atom/ns#' term='gamedev'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Simple Tic Tac Toe Game (c++)</title><content type='html'>I've seen a bunch of random people learning programming starting out with Tic Tac Toe games. It is an interesting challenge for beginners and I think its probably a great first-challenge to try once you think you're getting the hang of the language basics.&lt;br /&gt;&lt;br /&gt;I myself had never made a Tic Tac Toe game, but after seeing so much beginners having trouble with it, and seeing their code filled with un-necessary "bloat", I decided to try making a lean C++ console based tic tac toe game.&lt;br /&gt;&lt;br /&gt;The goal was to make a functional Tic Tac Toe game without the hundreds of lines other people's code usually takes.&lt;br /&gt;&lt;br /&gt;In my head I was thinking it might even be possible to do in as few as 30 lines, but that was a bit too optimistic for me in practice.&lt;br /&gt;Although if I didn't handle bad-cases, and didn't format the output nicely, I could probably do that; but the quality of a program should not be sacrificed for "less lines" of code, so I decided to handle all the bad-cases and such I'm aware of (which in turn increased the amount of code the program needed).&lt;br /&gt;&lt;br /&gt;Anyways here's the full code:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#include &amp;lt;conio.h&amp;gt;&lt;br /&gt;#include &amp;lt;iostream&amp;gt;&lt;br /&gt;using namespace std;&lt;br /&gt;&lt;br /&gt;void ticTacToe() {&lt;br /&gt;    char w = 0, b[9] = { '1','2','3','4','5','6','7','8','9' };&lt;br /&gt;    char player[][9] = { "Player O", "Player X" };&lt;br /&gt;    unsigned int slot = 0, turn = 1, moves = 0;&lt;br /&gt;    for(;;) {&lt;br /&gt;        system("cls");&lt;br /&gt;        cout &lt;&lt; "Tic Tac Toe!" &lt;&lt; endl &lt;&lt; endl;&lt;br /&gt;        cout &lt;&lt; "   " &lt;&lt; b[0] &lt;&lt; "|" &lt;&lt; b[1] &lt;&lt; "|" &lt;&lt; b[2] &lt;&lt; endl &lt;&lt; "   -+-+-" &lt;&lt; endl;&lt;br /&gt;        cout &lt;&lt; "   " &lt;&lt; b[3] &lt;&lt; "|" &lt;&lt; b[4] &lt;&lt; "|" &lt;&lt; b[5] &lt;&lt; endl &lt;&lt; "   -+-+-" &lt;&lt; endl;&lt;br /&gt;        cout &lt;&lt; "   " &lt;&lt; b[6] &lt;&lt; "|" &lt;&lt; b[7] &lt;&lt; "|" &lt;&lt; b[8] &lt;&lt; endl &lt;&lt; endl;&lt;br /&gt;        if (w || (++moves &gt; 9)) {&lt;br /&gt;            if (w) cout &lt;&lt; player[w=='X'] &lt;&lt; " is the winner!!!" &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl;&lt;br /&gt;            else   cout &lt;&lt; "No Winner!!!" &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl;&lt;br /&gt;            cin.clear(); cin.ignore(~0u&gt;&gt;1, '\n'); _getch();&lt;br /&gt;            return;&lt;br /&gt;        }&lt;br /&gt;        cout &lt;&lt; player[turn^=1] &lt;&lt; " Choose a Slot... ";&lt;br /&gt;        cin  &gt;&gt; slot;&lt;br /&gt;        if (slot &lt; 1 || slot &gt; 9 || b[slot-1] &gt; '9') {&lt;br /&gt;            cout &lt;&lt; "Please Choose A Valid Slot!!!" &lt;&lt; endl;&lt;br /&gt;            cin.clear(); cin.ignore(~0u&gt;&gt;1, '\n'); _getch();&lt;br /&gt;            turn^=1; moves--;&lt;br /&gt;            continue;&lt;br /&gt;        }&lt;br /&gt;        b[slot-1] = turn ? 'X' : 'O';&lt;br /&gt;        ((((b[0]==b[1]&amp;&amp;b[0]==b[2]&amp;&amp;(w=b[0])) || (b[3]==b[4]&amp;&amp;b[3]==b[5]&amp;&amp;(w=b[3]))&lt;br /&gt;        || (b[6]==b[7]&amp;&amp;b[6]==b[8]&amp;&amp;(w=b[6])))||((b[0]==b[3]&amp;&amp;b[0]==b[6]&amp;&amp;(w=b[0]))&lt;br /&gt;        || (b[1]==b[4]&amp;&amp;b[1]==b[7]&amp;&amp;(w=b[1])) || (b[2]==b[5]&amp;&amp;b[2]==b[8]&amp;&amp;(w=b[2])))&lt;br /&gt;        ||((b[0]==b[4]&amp;&amp;b[0]==b[8]&amp;&amp;(w=b[0])) || (b[2]==b[4]&amp;&amp;b[2]==b[6]&amp;&amp;(w=b[2])))));&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    for(;;) ticTacToe();&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The whole program ended up being 40 lines of code, which since it handles bad-cases, probably isn't that bad.&lt;br /&gt;&lt;br /&gt;I would like to point out how few If statements or Switch Statements are needed for a tic tac toe game as seen above.&lt;br /&gt;I usually see tic tac toe code examples filled with If/Switch statements that simply aren't necessary and make the code a lot bigger.&lt;br /&gt;&lt;br /&gt;If you dislike the code above then I somewhat agree that the code could be prettier. Since the goal was to keep the amount of code to a minimum, it limited me in my code cleanliness.&lt;br /&gt;&lt;br /&gt;If you notice, in my coding style there are times where I group more than one statement on the same line of code.&lt;br /&gt;This is my personal preference when it comes to short statements that go hand-in-hand with each other. There are some programmers that don't like this style of mine, and I respect that, but I like code that is structured pretty, and grouping similar short statements allows me to accomplish nicer looking code IMO.&lt;br /&gt;&lt;br /&gt;I kind-of lied with the title of this blog post though. Although this program is 'simple' in terms of 'little code', it isn't very 'simple' in terms of the ability for someone that isn't experienced with c++ to understand.&lt;br /&gt;I used some tricks which newer c++ programmers may have trouble with; and if you do wish to understand or ask about part of the code above don't hesitate to leave a comment.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4716010487178315883?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4716010487178315883/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/simple-tic-tac-toe-game-c.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4716010487178315883'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4716010487178315883'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/12/simple-tic-tac-toe-game-c.html' title='Simple Tic Tac Toe Game (c++)'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3852373378863500533</id><published>2010-11-24T23:33:00.008-05:00</published><updated>2010-11-25T00:39:02.445-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Virtual Key Code to String</title><content type='html'>If you ever used GetAsyncKeyState() or GetKeyState() or any other windows function using virtual keys, this post might be useful to you.&lt;br /&gt;&lt;br /&gt;There are certain situations where you might want to print out a string representation of the virtual key you're dealing with, and from what I've researched, I don't think there's an API function call that will do this for us, so I made my own.&lt;br /&gt;&lt;br /&gt;The following function will take as input a Virtual Key Code (e.g. VK_RETURN) and then return the string representation of the key (e.g. "VK_RETURN"). Of course it works for 'A' to 'Z' and digits as well (there are no VK_* macros for such virtual keys because they're the same as the ascii char representation).&lt;br /&gt;&lt;br /&gt;Here's the function, Its a big one so I've hidden it by default.&lt;br /&gt;&lt;a href="javascript:toggle();" id="displayText"&gt;Show Code&lt;/a&gt;&lt;br /&gt;&lt;div id="toggleText" style="display: none;"&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#define caseStringify(x) case x: return string(#x)&lt;br /&gt;&lt;br /&gt;string vkToString(int vk) {&lt;br /&gt;    char c[2] = {0};&lt;br /&gt;    if (vk &gt;= '0' &amp;&amp; vk &lt;= '9') { c[0]=(char)vk; return string(c); }&lt;br /&gt;    if (vk &gt;= 'A' &amp;&amp; vk &lt;= 'Z') { c[0]=(char)vk; return string(c); }&lt;br /&gt;    switch(vk) {&lt;br /&gt;        // VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)&lt;br /&gt;        // 0x40 : unassigned&lt;br /&gt;        // VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)&lt;br /&gt;        caseStringify(VK_LBUTTON);&lt;br /&gt;        caseStringify(VK_RBUTTON);&lt;br /&gt;        caseStringify(VK_CANCEL);&lt;br /&gt;        caseStringify(VK_MBUTTON);  // NOT contiguous with L &amp; RBUTTON&lt;br /&gt;        caseStringify(VK_XBUTTON1); // NOT contiguous with L &amp; RBUTTON&lt;br /&gt;        caseStringify(VK_XBUTTON2); // NOT contiguous with L &amp; RBUTTON&lt;br /&gt;        caseStringify(VK_BACK);&lt;br /&gt;        caseStringify(VK_TAB);&lt;br /&gt;        caseStringify(VK_CLEAR);&lt;br /&gt;        caseStringify(VK_RETURN);&lt;br /&gt;        caseStringify(VK_SHIFT);&lt;br /&gt;        caseStringify(VK_CONTROL);&lt;br /&gt;        caseStringify(VK_MENU);&lt;br /&gt;        caseStringify(VK_PAUSE);&lt;br /&gt;        caseStringify(VK_CAPITAL);&lt;br /&gt;        caseStringify(VK_KANA);&lt;br /&gt;        caseStringify(VK_JUNJA);&lt;br /&gt;        caseStringify(VK_FINAL);&lt;br /&gt;        caseStringify(VK_KANJI);&lt;br /&gt;        caseStringify(VK_ESCAPE);&lt;br /&gt;        caseStringify(VK_CONVERT);&lt;br /&gt;        caseStringify(VK_NONCONVERT);&lt;br /&gt;        caseStringify(VK_ACCEPT);&lt;br /&gt;        caseStringify(VK_MODECHANGE);&lt;br /&gt;        caseStringify(VK_SPACE);&lt;br /&gt;        caseStringify(VK_PRIOR);&lt;br /&gt;        caseStringify(VK_NEXT);&lt;br /&gt;        caseStringify(VK_END);&lt;br /&gt;        caseStringify(VK_HOME);&lt;br /&gt;        caseStringify(VK_LEFT);&lt;br /&gt;        caseStringify(VK_UP);&lt;br /&gt;        caseStringify(VK_RIGHT);&lt;br /&gt;        caseStringify(VK_DOWN);&lt;br /&gt;        caseStringify(VK_SELECT);&lt;br /&gt;        caseStringify(VK_PRINT);&lt;br /&gt;        caseStringify(VK_EXECUTE);&lt;br /&gt;        caseStringify(VK_SNAPSHOT);&lt;br /&gt;        caseStringify(VK_INSERT);&lt;br /&gt;        caseStringify(VK_DELETE);&lt;br /&gt;        caseStringify(VK_HELP);&lt;br /&gt;        caseStringify(VK_LWIN);&lt;br /&gt;        caseStringify(VK_RWIN);&lt;br /&gt;        caseStringify(VK_APPS);&lt;br /&gt;        caseStringify(VK_SLEEP);&lt;br /&gt;        caseStringify(VK_NUMPAD0);&lt;br /&gt;        caseStringify(VK_NUMPAD1);&lt;br /&gt;        caseStringify(VK_NUMPAD2);&lt;br /&gt;        caseStringify(VK_NUMPAD3);&lt;br /&gt;        caseStringify(VK_NUMPAD4);&lt;br /&gt;        caseStringify(VK_NUMPAD5);&lt;br /&gt;        caseStringify(VK_NUMPAD6);&lt;br /&gt;        caseStringify(VK_NUMPAD7);&lt;br /&gt;        caseStringify(VK_NUMPAD8);&lt;br /&gt;        caseStringify(VK_NUMPAD9);&lt;br /&gt;        caseStringify(VK_MULTIPLY);&lt;br /&gt;        caseStringify(VK_ADD);&lt;br /&gt;        caseStringify(VK_SEPARATOR);&lt;br /&gt;        caseStringify(VK_SUBTRACT);&lt;br /&gt;        caseStringify(VK_DECIMAL);&lt;br /&gt;        caseStringify(VK_DIVIDE);&lt;br /&gt;        caseStringify(VK_F1);&lt;br /&gt;        caseStringify(VK_F2);&lt;br /&gt;        caseStringify(VK_F3);&lt;br /&gt;        caseStringify(VK_F4);&lt;br /&gt;        caseStringify(VK_F5);&lt;br /&gt;        caseStringify(VK_F6);&lt;br /&gt;        caseStringify(VK_F7);&lt;br /&gt;        caseStringify(VK_F8);&lt;br /&gt;        caseStringify(VK_F9);&lt;br /&gt;        caseStringify(VK_F10);&lt;br /&gt;        caseStringify(VK_F11);&lt;br /&gt;        caseStringify(VK_F12);&lt;br /&gt;        caseStringify(VK_F13);&lt;br /&gt;        caseStringify(VK_F14);&lt;br /&gt;        caseStringify(VK_F15);&lt;br /&gt;        caseStringify(VK_F16);&lt;br /&gt;        caseStringify(VK_F17);&lt;br /&gt;        caseStringify(VK_F18);&lt;br /&gt;        caseStringify(VK_F19);&lt;br /&gt;        caseStringify(VK_F20);&lt;br /&gt;        caseStringify(VK_F21);&lt;br /&gt;        caseStringify(VK_F22);&lt;br /&gt;        caseStringify(VK_F23);&lt;br /&gt;        caseStringify(VK_F24);&lt;br /&gt;        caseStringify(VK_NUMLOCK);&lt;br /&gt;        caseStringify(VK_SCROLL);&lt;br /&gt;        caseStringify(VK_OEM_NEC_EQUAL);  // '=' key on numpad&lt;br /&gt;        caseStringify(VK_OEM_FJ_MASSHOU); // 'Unregister word' key&lt;br /&gt;        caseStringify(VK_OEM_FJ_TOUROKU); // 'Register word' key&lt;br /&gt;        caseStringify(VK_OEM_FJ_LOYA);    // 'Left OYAYUBI' key&lt;br /&gt;        caseStringify(VK_OEM_FJ_ROYA);    // 'Right OYAYUBI' key&lt;br /&gt;        caseStringify(VK_LSHIFT);&lt;br /&gt;        caseStringify(VK_RSHIFT);&lt;br /&gt;        caseStringify(VK_LCONTROL);&lt;br /&gt;        caseStringify(VK_RCONTROL);&lt;br /&gt;        caseStringify(VK_LMENU);&lt;br /&gt;        caseStringify(VK_RMENU);&lt;br /&gt;        caseStringify(VK_BROWSER_BACK);&lt;br /&gt;        caseStringify(VK_BROWSER_FORWARD);&lt;br /&gt;        caseStringify(VK_BROWSER_REFRESH);&lt;br /&gt;        caseStringify(VK_BROWSER_STOP);&lt;br /&gt;        caseStringify(VK_BROWSER_SEARCH);&lt;br /&gt;        caseStringify(VK_BROWSER_FAVORITES);&lt;br /&gt;        caseStringify(VK_BROWSER_HOME);&lt;br /&gt;        caseStringify(VK_VOLUME_MUTE);&lt;br /&gt;        caseStringify(VK_VOLUME_DOWN);&lt;br /&gt;        caseStringify(VK_VOLUME_UP);&lt;br /&gt;        caseStringify(VK_MEDIA_NEXT_TRACK);&lt;br /&gt;        caseStringify(VK_MEDIA_PREV_TRACK);&lt;br /&gt;        caseStringify(VK_MEDIA_STOP);&lt;br /&gt;        caseStringify(VK_MEDIA_PLAY_PAUSE);&lt;br /&gt;        caseStringify(VK_LAUNCH_MAIL);&lt;br /&gt;        caseStringify(VK_LAUNCH_MEDIA_SELECT);&lt;br /&gt;        caseStringify(VK_LAUNCH_APP1);&lt;br /&gt;        caseStringify(VK_LAUNCH_APP2);&lt;br /&gt;        caseStringify(VK_OEM_1);      // ';:' for US&lt;br /&gt;        caseStringify(VK_OEM_PLUS);   // '+' any country&lt;br /&gt;        caseStringify(VK_OEM_COMMA);  // ',' any country&lt;br /&gt;        caseStringify(VK_OEM_MINUS);  // '-' any country&lt;br /&gt;        caseStringify(VK_OEM_PERIOD); // '.' any country&lt;br /&gt;        caseStringify(VK_OEM_2);  // '/?' for US&lt;br /&gt;        caseStringify(VK_OEM_3);  // '`~' for US&lt;br /&gt;        caseStringify(VK_OEM_4);  //  '[{' for US&lt;br /&gt;        caseStringify(VK_OEM_5);  //  '\|' for US&lt;br /&gt;        caseStringify(VK_OEM_6);  //  ']}' for US&lt;br /&gt;        caseStringify(VK_OEM_7);  //  ''"' for US&lt;br /&gt;        caseStringify(VK_OEM_8);&lt;br /&gt;        caseStringify(VK_OEM_AX);   //  'AX' key on Japanese AX kbd&lt;br /&gt;        caseStringify(VK_OEM_102);  //  "&lt;&gt;" or "\|" on RT 102-key kbd.&lt;br /&gt;        caseStringify(VK_ICO_HELP); //  Help key on ICO&lt;br /&gt;        caseStringify(VK_ICO_00);   //  00 key on ICO&lt;br /&gt;        caseStringify(VK_PROCESSKEY);&lt;br /&gt;        caseStringify(VK_ICO_CLEAR);&lt;br /&gt;        caseStringify(VK_PACKET);&lt;br /&gt;    }&lt;br /&gt;    c[0]=(char)vk;&lt;br /&gt;    return string(c);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;I ended up needing this on my NES emulator in order to display mapped-keyboard settings. That's probably where other people will need it too.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In case you've never seen something like this and you're wondering how it works, it uses a powerful and very useful feature of the C/C++ preprocessor called 'stringification'.&lt;br /&gt;&lt;br /&gt;Essentially you take convert arguments to a macro into string representations.&lt;br /&gt;Here's more info:&lt;br /&gt;http://gcc.gnu.org/onlinedocs/cpp/Stringification.html&lt;br /&gt;&lt;br /&gt;I took the winapi macros for the virtual keys and wrapped them in a macro that converts them to strings. Mostly was just copy-paste and regex replace work.&lt;br /&gt;Anyways have fun :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3852373378863500533?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3852373378863500533/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/11/virtual-key-code-to-string.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3852373378863500533'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3852373378863500533'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/11/virtual-key-code-to-string.html' title='Virtual Key Code to String'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-225308306910754541</id><published>2010-10-11T00:57:00.008-04:00</published><updated>2010-10-11T01:21:24.612-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Easy generic toString() function in C++</title><content type='html'>In c++ you can make a simple toString() template function that converts primitives to a string.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#include &amp;lt;iostream&amp;gt;&lt;br /&gt;using namespace std;&lt;br /&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;string toString(T t) {&lt;br /&gt;    stringstream s;&lt;br /&gt;    s &lt;&lt; t;&lt;br /&gt;    return s.str();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This will work for any type that defines the &lt;&lt; operator for use with streams.&lt;br /&gt;&lt;br /&gt;So with this simple one function we have an "int to string" function, a "float to string" function, a "double to string" function, etc...&lt;br /&gt;&lt;br /&gt;Using it is of course simple:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    string s0 = toString(100);&lt;br /&gt;    string s1 = toString(100.1f);&lt;br /&gt;    string s2 = toString(100.12);&lt;br /&gt;    cout &lt;&lt; s0 &lt;&lt; " " &lt;&lt; s1 &lt;&lt; " " &lt;&lt; s2 &lt;&lt; endl;&lt;br /&gt;    return 0; // Prints out "100 100.1 100.12"&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-225308306910754541?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/225308306910754541/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/10/easy-generic-tostring-function-in-c.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/225308306910754541'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/225308306910754541'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/10/easy-generic-tostring-function-in-c.html' title='Easy generic toString() function in C++'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-8833141938645130130</id><published>2010-09-27T18:11:00.012-04:00</published><updated>2010-10-09T00:02:25.150-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bugs'/><category scheme='http://www.blogger.com/atom/ns#' term='shaders'/><category scheme='http://www.blogger.com/atom/ns#' term='fun'/><category scheme='http://www.blogger.com/atom/ns#' term='emulation'/><category scheme='http://www.blogger.com/atom/ns#' term='NES'/><category scheme='http://www.blogger.com/atom/ns#' term='cottonNES'/><title type='text'>Fun Shader Bugs</title><content type='html'>Yesterday I ran into a funny bug when implementing an Eagle2x pixel shader.&lt;br /&gt;&lt;br /&gt;I think the picture speaks for itself xD&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_WwIahqE-1Co/TKEXSv-ElqI/AAAAAAAAACY/4OQOS3MGJNQ/s1600/7.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 316px; height: 320px;" src="http://2.bp.blogspot.com/_WwIahqE-1Co/TKEXSv-ElqI/AAAAAAAAACY/4OQOS3MGJNQ/s320/7.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5521720229014836898" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;center&gt;(Click the picture to see the magnified version and spot the bug :D)&lt;/center&gt;&lt;br /&gt;&lt;br /&gt;Funny thing is the bug wasn't actually caused by the shader itself, instead it was due to the way I applied the shader. On my emu I had 3 separate textures for Sprite Background, Sprite Foreground, and Tile Background. Then I would render all 3 of these textures to the output buffer. When I applied the shader it applied it to each individual layer (sprite/bg) instead of the picture as a whole. The sprite layers for instance were just a few sprites with a lot of transparency, and running the Eagle2x algorithm on this layer caused artifacts.&lt;br /&gt;&lt;br /&gt;The solution then was to combine all 3 layers into 1 texture before applying the shader; using 1-complete texture fixed the cause of the artifacts. I ended up coming up with some pretty cool bitwise-based merge function which combined 3 bitmaps arrays according to priority and transparency without having to use any conditional statements.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void combineLayers() {&lt;br /&gt;    for(int y = 0; y &lt; bHeight; y++) {&lt;br /&gt;    for(int x = 0; x &lt; bWidth;  x++) {&lt;br /&gt;        s32 m0 = ((s32)(buffer[0][y][x])) &gt;&gt; 31;&lt;br /&gt;        s32 m1 = ((s32)(buffer[1][y][x])) &gt;&gt; 31;&lt;br /&gt;        s32 m2 = ((s32)(buffer[2][y][x])) &gt;&gt; 31;&lt;br /&gt;        m0 &amp;= ~m1 &amp; ~m2; m1 &amp;= ~m2;&lt;br /&gt;        buffer[0][y][x]  = buffer[0][y][x] &amp; m0;&lt;br /&gt;        buffer[0][y][x] |= buffer[1][y][x] &amp; m1;&lt;br /&gt;        buffer[0][y][x] |= buffer[2][y][x] &amp; m2;&lt;br /&gt;    }}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Essentially the code creates masks by checking if the MSB is set (since the most significant byte is 0xff on non-transparent pixels, and 0x00 on transparent pixels, the most-significant bit is set when non-transparent; of-course this code won't work properly with partial-transparencies).&lt;br /&gt;After it creates the masks, it uses some bitwise math to make sure the pixel with the highest priority is the one that is shown, and leaves the resulting pixel in the buffer[0] bitmap layer.&lt;br /&gt;Note: The priority is (buffer[2] &gt; buffer[1] &gt; buffer[0]). So the pixel in buffer[2] is the top-most.&lt;br /&gt;&lt;br /&gt;I initially had thought this bitwise version would be faster than a version using conditionals, but I was wrong. The compiled code for this is pretty bloated. Instead the conditional version compiles to much better optimized code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void combineLayers() {&lt;br /&gt;    for(int y = 0; y &lt; bHeight; y++) {&lt;br /&gt;    for(int x = 0; x &lt; bWidth;  x++) {&lt;br /&gt;        if  (buffer[2][y][x] &gt;&gt; 31) buffer[0][y][x] = buffer[2][y][x];&lt;br /&gt;        elif(buffer[1][y][x] &gt;&gt; 31) buffer[0][y][x] = buffer[1][y][x];&lt;br /&gt;        elif(buffer[0][y][x] &gt;&gt; 31) buffer[0][y][x] = buffer[0][y][x];&lt;br /&gt;        else                        buffer[0][y][x] = 0;&lt;br /&gt;    }}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So I guess the lesson learned here is that many times using conditionals are better than complex bitwise operations. Even though the bitwise versions may seem more clever and quicker on first impression.&lt;br /&gt;&lt;br /&gt;Note: "elif" in the above code is a macro for "else if"&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#define elif else if&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I like the elif macro because it keeps code more compact. Using "else if" almost always messes up text alignment and due to having too much letters.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-8833141938645130130?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/8833141938645130130/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/fun-shader-bugs.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8833141938645130130'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8833141938645130130'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/fun-shader-bugs.html' title='Fun Shader Bugs'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_WwIahqE-1Co/TKEXSv-ElqI/AAAAAAAAACY/4OQOS3MGJNQ/s72-c/7.png' height='72' width='72'/><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6909319145714779492</id><published>2010-09-26T23:37:00.005-04:00</published><updated>2010-09-27T00:32:36.757-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='shaders'/><category scheme='http://www.blogger.com/atom/ns#' term='emulation'/><category scheme='http://www.blogger.com/atom/ns#' term='NES'/><category scheme='http://www.blogger.com/atom/ns#' term='cottonNES'/><title type='text'>cottonNES - More Progress...</title><content type='html'>&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_WwIahqE-1Co/TKARs-aTimI/AAAAAAAAACQ/5NQITLA4W8o/s1600/6.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 198px; height: 200px;" src="http://1.bp.blogspot.com/_WwIahqE-1Co/TKARs-aTimI/AAAAAAAAACQ/5NQITLA4W8o/s200/6.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5521432607521475170" /&gt;&lt;/a&gt;So I have been working diligently on cottonNES, and have made some progress over my last update.&lt;br /&gt;&lt;br /&gt;As far as the core goes, I've been able to pass some more cpu/ppu tests, but my emu still fails many of blargg's timing tests (those things are brutal!). I already switched my cpu core to a cycle-accurate design, this proves to be needed for a few games (Ms. Pacman, Bad Dudes, Baseball Stars 2, etc...). Whats cool is my emu now runs Battletoads and Battletoads &amp; Double Dragons, these 2 games are very timing sensitive and many NES emulators still fail to run them properly (some even crash...). That said, the games still have graphical problems, but at least they go in-game.&lt;br /&gt;&lt;br /&gt;Something else I implemented was joypad support. Currently its just hard-coded to match my ps3-controller, but in the future I'll do a fancy configuration screen. I ended up going with SDL for the joypad API because I just wanted something simple to use. Perhaps in the future I will rewrite the code with direct-input since i wasn't very satisfied with SDL.&lt;br /&gt;&lt;br /&gt;The last big thing I did was support for pixel shaders! I'm a shader noob, but between yesterday and today I've learned enough of HLSL to make 2 shaders. One shader is a scanline shader, and the other is a Scale3x shader. The cool thing is this offloads the filtering onto the GPU so the CPU can do less work, overall the Scale3x filter was about 54% faster than my C++ based attempt (222fps vs 144fps in a scene). In the Super Mario Bros 2 pic above, I have the Scale3x shader on so you can see what it looks like.&lt;br /&gt;&lt;br /&gt;Anyways, I still have a lot more work to do with my emulator before its ready for a release; particularly PPU and APU need more work since they're the cause of most problems I'm having now. I hope I continue to be motivated so that cottonNES can become one of the better NES emulators out there; I feel it has the potential, but it just depends on if I continue working on it.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6909319145714779492?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6909319145714779492/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/cottonnes-more-progress.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6909319145714779492'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6909319145714779492'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/cottonnes-more-progress.html' title='cottonNES - More Progress...'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_WwIahqE-1Co/TKARs-aTimI/AAAAAAAAACQ/5NQITLA4W8o/s72-c/6.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5822338840750043103</id><published>2010-09-16T04:21:00.013-04:00</published><updated>2010-09-27T00:32:13.842-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='emulation'/><category scheme='http://www.blogger.com/atom/ns#' term='NES'/><category scheme='http://www.blogger.com/atom/ns#' term='cottonNES'/><title type='text'>NES emu progress</title><content type='html'>&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHXswwCR7I/AAAAAAAAACI/tg08KT3EAag/s1600/5.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 190px; height: 200px;" src="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHXswwCR7I/AAAAAAAAACI/tg08KT3EAag/s200/5.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5517428182506162098" /&gt;&lt;/a&gt;For those that don't know, I had started a NES emu project from scratch a while back, but then I got bored and stopped working on it in favor of some other projects.&lt;br /&gt;This past week I have regained my interest in it and have made some progress.&lt;br /&gt;After some hours of debugging, it now passes all normal opcode tests in Kevin Horton's nestest.nes rom.&lt;br /&gt;Last week it failed most of those tests miserably (turns out I was just setting wrong flags in a few opcodes like BIT and PLP).&lt;br /&gt;&lt;br /&gt;I currently have mappers 0(no-mapper),1,2,3,4,and 7 implemented. I think mapper #1 has a few bugs and mapper #4 needs to have its IRQ timer code redone later on to be more accurate (but its okay for now).&lt;br /&gt;Mappers 2,3, and 7 are kind-of fun because they're so easy to implement. Each can be done in just a few lines of code.&lt;br /&gt;&lt;br /&gt;For example, my Mapper #2 implementation is just:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;class Mapper2: public Mapper {&lt;br /&gt;public:&lt;br /&gt;    Mapper2()          { Init(); }&lt;br /&gt;    virtual ~Mapper2() { Close(); }&lt;br /&gt;    void WritePROM(u16 addr, u8 value) {&lt;br /&gt;        clamp(value, ROM.romBanks, "Mapper2: PROM");&lt;br /&gt;        PROM_SLOT[0] = _PROM[value*2+0];&lt;br /&gt;        PROM_SLOT[1] = _PROM[value*2+1];&lt;br /&gt;    }&lt;br /&gt;};&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Something I've noticed when browsing through other NES emu's source-code, is that many of the emulators have horribly messy code. There is one popular emulator that uses OOP too much. When this happens it fucks up intellisense and makes browsing code a PITA. You right click on any method to go to the definition and intellisense finds ~50 possible matches and makes you chose manually which method is the one you're looking for. This always happens in projects that use too much OOP and is a very annoying problem.&lt;br /&gt;&lt;br /&gt;Another popular emulator does the opposite; it doesn't use any OOP even though the code is now in c++ (I guess originally it was in C). Anyways the whole code is very C-like and abuses macros like crazy, this makes everything a mess. Its a common mistake to abuse macros; I did it when I started with c++, but any good coder knows that you should only use macros when there's no better way. Oh and the code uses 2-space tabbing which is ridiculous.&lt;br /&gt;&lt;br /&gt;On the subject of macros, its more understandable to see macro usage in C code compared to C++ code. This is because C is very limited compared to C++, and there is a lot more stuff you can't do so you use macros to simulate these features. In C++ however you have templates and references which can help you remove the need for many macros. This is a big reason why C++ is better than C.&lt;br /&gt;Many C-programmers move on to C++ and still code C-like because they don't know proper C++, that could be the case with the nes-emu I looked at. Anyways I suppose I'll save a C/C++ comparison rant for another blog post.&lt;br /&gt;&lt;br /&gt;So back to talking about my emulator, cottonNES...&lt;br /&gt;My emulator is no-where near ready for a release. Although it boots hundreds of games now that the big cpu bugs are fixed, it still has problems in many games (most-likely to do with PPU and timing issues...).&lt;br /&gt;&lt;br /&gt;I would like to continue discussing nes emulation further here, but sadly I have an exam this week and need to study D:&lt;br /&gt;&lt;br /&gt;I suppose this post will be boring without screen-shots :D&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_WwIahqE-1Co/TJHWZgjyhSI/AAAAAAAAABw/rO-K2TjrjM4/s1600/1.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 192px; height: 200px;" src="http://4.bp.blogspot.com/_WwIahqE-1Co/TJHWZgjyhSI/AAAAAAAAABw/rO-K2TjrjM4/s200/1.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5517426752230688034" /&gt;&lt;/a&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHWkFPVn8I/AAAAAAAAAB4/q1Bksp21OMI/s1600/2.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 191px; height: 200px;" src="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHWkFPVn8I/AAAAAAAAAB4/q1Bksp21OMI/s200/2.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5517426933875711938" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHWP3JuwzI/AAAAAAAAABo/ySfHGJw8BII/s1600/3.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 192px; height: 200px;" src="http://1.bp.blogspot.com/_WwIahqE-1Co/TJHWP3JuwzI/AAAAAAAAABo/ySfHGJw8BII/s200/3.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5517426586496713522" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_WwIahqE-1Co/TJHWsIRX0QI/AAAAAAAAACA/1w1m2sqOb0A/s1600/4.png"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 191px; height: 200px;" src="http://3.bp.blogspot.com/_WwIahqE-1Co/TJHWsIRX0QI/AAAAAAAAACA/1w1m2sqOb0A/s200/4.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5517427072128504066" /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5822338840750043103?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5822338840750043103/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/nes-emu-progress.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5822338840750043103'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5822338840750043103'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/nes-emu-progress.html' title='NES emu progress'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_WwIahqE-1Co/TJHXswwCR7I/AAAAAAAAACI/tg08KT3EAag/s72-c/5.png' height='72' width='72'/><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6609569892137257099</id><published>2010-09-04T23:13:00.005-04:00</published><updated>2010-09-05T01:00:15.352-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Using the volatile keyword to prevent float precision problems</title><content type='html'>Consider the following code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    for(float i = 0; i &lt; 100; i++) {&lt;br /&gt;        float f = i / 100.0f;&lt;br /&gt;        if (f  != i / 100.0f) {&lt;br /&gt;            cout &lt;&lt; i &lt;&lt; ", ";&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    cout &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;One should expect the above code to not print out anything, since the 2 operations are obviously equal.&lt;br /&gt;Ironically, if you compile this code in msvc or gcc, you will most-likely get a bunch of numbers spammed to the console.&lt;br /&gt;&lt;br /&gt;Why is this? Well it seems that the compilers take liberties with floating point calculations; even though you're dealing with single-precision 32bit floats, the compilers may use the full 80bit precision of the x87 FPU in calculations, or may even use double-floating point arithmetic for one of the operations, and use single-floating point for another one... mix and matching precisions, causing problems...&lt;br /&gt;In the end, the different precision of the operations will cause the results of two seemingly equal operations to be unequal.&lt;br /&gt;&lt;br /&gt;One solution is to use the volatile keyword.&lt;br /&gt;The volatile keyword essentially makes the compiler always write-back values to memory once an operation is preformed, and it always reloads the value from memory when it will be used again.&lt;br /&gt;This allows us to force the compiler to truncate the values to 32bit floats when it writes them to memory, and when it loads the value again it will be limited to the precision of a 32bit float.&lt;br /&gt;&lt;br /&gt;So now we can do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    for(float i = 0; i &lt; 100; i++) {&lt;br /&gt;        volatile float f1 = i / 100.0f;&lt;br /&gt;        volatile float f2 = i / 100.0f;&lt;br /&gt;        if (f1 != f2) {&lt;br /&gt;            cout &lt;&lt; i &lt;&lt; ", ";&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    cout &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This will fix the problems we were having before, and not print out anything.&lt;br /&gt;&lt;br /&gt;There are many papers and discussions about ways to compare floating point values, and I won't go into more detail here.&lt;br /&gt;&lt;a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm"&gt;This site&lt;/a&gt; lists a few methods, and the problems they could have.&lt;br /&gt;So I suggest reading that if you're interested.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6609569892137257099?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6609569892137257099/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/using-volatile-keyword-to-prevent-float.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6609569892137257099'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6609569892137257099'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/09/using-volatile-keyword-to-prevent-float.html' title='Using the volatile keyword to prevent float precision problems'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2780125452620596160</id><published>2010-08-22T02:39:00.011-04:00</published><updated>2010-09-05T00:56:21.802-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='misconceptions'/><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>32bit Floats - Integer Accuracy and Interesting Consequences</title><content type='html'>There are big misconceptions I've seen regarding the accuracy of floats.&lt;br /&gt;One professor of mine even went as far as to say, the computer might not store "2" as "2.0", but rather "2.000019" if using floats.&lt;br /&gt;This is not true.&lt;br /&gt;&lt;br /&gt;32-bit floats can actually represent quite a large amount of integer values 100% accurately.&lt;br /&gt;&lt;br /&gt;The exact integer-range a 32bit float can represent accurately is -16777216 to 16777216.&lt;br /&gt;This means that it is roughly equivalent to a 25-bit signed integer, which has the range -16777216 to 16777215.&lt;br /&gt;&lt;br /&gt;If you only care about positive values, then the float is equivalent to a 24-bit unsigned integer, which has the range 0 to 16777215.&lt;br /&gt;&lt;br /&gt;I commonly see these values messed up, with people saying a float can only represent a 24-bit signed integer (which would be -8388608 to 8388607, which is wrong).&lt;br /&gt;&lt;br /&gt;Below I made a test case to prove the floating point range by exhaustive search.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int testFloatRange(bool pos) {&lt;br /&gt;    volatile int    i = 0;&lt;br /&gt;    volatile float  f = 0.0f;&lt;br /&gt;    volatile double d = 0.0;&lt;br /&gt;    for (;;) {&lt;br /&gt;        volatile double t = (double)(float)i;&lt;br /&gt;        if ((double)f != d || (int)f != i || t != d) break;&lt;br /&gt;        if (pos) { f++; d++; i++; }&lt;br /&gt;        else     { f--; d--; i--; }&lt;br /&gt;    }&lt;br /&gt;    printf("%f != %d\n", f, i);&lt;br /&gt;    return pos ? (i-1) : (i+1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int _tmain(int argc, _TCHAR* argv[]) {&lt;br /&gt;    int p = testFloatRange(1);&lt;br /&gt;    int n = testFloatRange(0);&lt;br /&gt;    printf("Positive Range = 0 to %d\n", p);&lt;br /&gt;    printf("Negative Range = %d to 0\n", n);&lt;br /&gt;    printf("Full Range = %d to %d\n", n, p);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now its pretty interesting what happens once a 32-bit float reaches its limit of 16777216.&lt;br /&gt;If you try to increase the float by 1 when it has this value, the float will actually stay the same. This means if you try to increment a float by 1 in a loop, you will never get past 16777216! It will just get stuck in an infinite loop.&lt;br /&gt;&lt;br /&gt;Here is some proof of that:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int _tmain(int argc, _TCHAR* argv[]) {&lt;br /&gt;    volatile float f = 0xffffff-100; &lt;br /&gt;    for( ; f &lt; 0xffffff+100; f++) {&lt;br /&gt;        printf("Value = %f, Binary Representation (0x%x)\n", f, (int&amp;)f);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The programs output is:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;...&lt;br /&gt;Value = 16777214.000000, Binary Representation (0x4b7ffffe)&lt;br /&gt;Value = 16777215.000000, Binary Representation (0x4b7fffff)&lt;br /&gt;Value = 16777216.000000, Binary Representation (0x4b800000)&lt;br /&gt;Value = 16777216.000000, Binary Representation (0x4b800000)&lt;br /&gt;... Keeps repeating the last line infinitely...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Admittingly, I didn't know this infinite looping behavior until I made the test-case. This is something you should definitely watch out for.&lt;br /&gt;&lt;br /&gt;Oh and btw, you might be wondering why I was using "volatile float" in the above test-cases, instead of just "float". The "volatile" keyword is useful to use when we need to compare floats with their exact precision. I'll probably explain why in &lt;a href="http://cottonvibes.blogspot.com/2010/09/using-volatile-keyword-to-prevent-float.html"&gt;another article&lt;/a&gt; :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2780125452620596160?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2780125452620596160/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/32bit-floats-integer-accuracy-and.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2780125452620596160'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2780125452620596160'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/32bit-floats-integer-accuracy-and.html' title='32bit Floats - Integer Accuracy and Interesting Consequences'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2267537016263038178</id><published>2010-08-20T19:06:00.007-04:00</published><updated>2010-08-20T20:13:54.040-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Checking if a Float is a Power of 2</title><content type='html'>&lt;a href="http://cottonvibes.blogspot.com/2010/08/checking-if-integer-is-power-of-2.html"&gt;Last article&lt;/a&gt; I showed bitwise ways to check if integers are powers of 2, for completeness I'll show bitwise ways to check if floats are powers of 2.&lt;br /&gt;&lt;br /&gt;For floating point numbers, remember that they're represented in the form |S*1|E*8|M*23|.&lt;br /&gt;S = Sign Bit (1-bit)&lt;br /&gt;E = Exponent (8-bits)&lt;br /&gt;M = Mantissa (23-bits)&lt;br /&gt;&lt;br /&gt;Check out the IEEE-754 standard for more info:&lt;br /&gt;http://en.wikipedia.org/wiki/IEEE_754-1985&lt;br /&gt;&lt;br /&gt;The exponent is actually used to compute powers of 2, which is then multiplied by the mantissa, which has an implicitly hidden '1.' in front of it.&lt;br /&gt;&lt;br /&gt;So when we're checking if a float is a power of two, all we have to do is check if the mantissa is 0, and the exponent is non-zero (when the exponent is zero, the result is zero when the mantissa is also zero, or a denormal value when the mantissa is non-zero, so we don't want to consider these as powers of two).&lt;br /&gt;&lt;br /&gt;The code ends up looking like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;typedef unsigned __int32 u32;&lt;br /&gt;&lt;br /&gt;bool isPow2(float f) {&lt;br /&gt;    u32&amp; i = (u32&amp;)f;&lt;br /&gt;    u32  e = (i&gt;&gt;23) &amp; 0xff;&lt;br /&gt;    u32  m =  i &amp; 0x7fffff;&lt;br /&gt;    return !m &amp;&amp; e;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This however will end up counting negative-exponent powers of 2 (such as 2^-1 = 0.5), if this is not desirable, then we can modify the code to only count non-negative exponents (2^0 = 1, 2^1 = 2,...)&lt;br /&gt;&lt;br /&gt;The modified code looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(float f) {&lt;br /&gt;    u32&amp; i = (u32&amp;)f;&lt;br /&gt;    u32  e = (i&gt;&gt;23) &amp; 0xff;&lt;br /&gt;    u32  m =  i &amp; 0x7fffff;&lt;br /&gt;    return !m &amp;&amp; e &gt;= 127;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;One last thing, both these versions will also consider negative powers of two (such as -4, -2, -1) to be powers of two.&lt;br /&gt;If this is also undesirable, then we just need to check the Sign-bit of the float to determine if its negative, and if it is, then we will return false.&lt;br /&gt;&lt;br /&gt;This last function returns true if the float is a positive power of two with a positive exponent (1, 2, 4, 8, 16...).&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(float f) {&lt;br /&gt;    u32&amp; i = (u32&amp;)f;&lt;br /&gt;    u32  s =  i&gt;&gt;31;&lt;br /&gt;    u32  e = (i&gt;&gt;23) &amp; 0xff;&lt;br /&gt;    u32  m =  i &amp; 0x7fffff;&lt;br /&gt;    return !s &amp;&amp; !m &amp;&amp; e &gt;= 127;&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2267537016263038178?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2267537016263038178/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/checking-if-float-is-power-of-2.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2267537016263038178'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2267537016263038178'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/checking-if-float-is-power-of-2.html' title='Checking if a Float is a Power of 2'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-1453578986847491542</id><published>2010-08-20T02:42:00.010-04:00</published><updated>2010-08-20T03:52:47.749-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Checking if an Integer is a Power of 2</title><content type='html'>There are a few ways to check if an integer is a power of 2; some better than others.&lt;br /&gt;&lt;br /&gt;One crucial thing to notice for power-of-two integers, is that in their binary representation, they only have 1 bit set.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;0001 = 1&lt;br /&gt;0010 = 2&lt;br /&gt;0100 = 4&lt;br /&gt;1000 = 8&lt;br /&gt;... and so on...&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So one approach we can do to check if an integer is a power of two, is to just loop through the bits, and check if only 1 bit is set.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(uint n) {&lt;br /&gt;    const uint len = sizeof(uint)*8; // 32 for 4-byte integers&lt;br /&gt;    uint count = 0;&lt;br /&gt;    for(uint i = 0; i &lt; len; i++) {&lt;br /&gt;        count += n &amp; 1;&lt;br /&gt;        n &gt;&gt;= 1;&lt;br /&gt;    }&lt;br /&gt;    return count == 1;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now the above approach is pretty obvious and simple; but its not that nice considering we have to loop for every bit (32 times for 4-byte integers).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;There's a popular bitwise trick for determining if an integer is a power of 2, and it looks like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(uint n) {&lt;br /&gt;    return (n &amp; (n-1)) == 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now this is a lot nicer than our loop version. Instead of looping 32 times, we do just a few bitwise calculations.&lt;br /&gt;&lt;br /&gt;I was playing around with bitwise operations earlier today, and I discovered another bitwise method for checking powers of 2.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(uint n) {&lt;br /&gt;    return (n &amp; -n) == n;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I was really excited because I found this one out on my own, and I thought I had discovered it. However I did a google search on it, and I found out that this trick is already known :(&lt;br /&gt;&lt;br /&gt;The nice thing about this second bitwise version, compared to the more popular version above it, is that its a lot simpler to remember IMO. Speed-wise, they're both around the same, I suppose it depends on your target architecture on which one is actually fastest, but in practical purposes it probably doesn't matter which one you use.&lt;br /&gt;&lt;br /&gt;Note:&lt;br /&gt;Its important to mention that both of the bitwise methods mentioned above, will incorrectly treat zero as a power of two.&lt;br /&gt;To fix this behavior you can modify the functions like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(uint n) {&lt;br /&gt;    return n &amp;&amp; ((n &amp; (n-1)) == 0);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;and...&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;bool isPow2(uint n) {&lt;br /&gt;    return n &amp;&amp; ((n &amp; -n) == n);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Sadly this adds an extra conditional to our fast bitwise methods, however it still ends up being a lot nicer (and faster) than our initial loop version.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-1453578986847491542?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/1453578986847491542/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/checking-if-integer-is-power-of-2.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1453578986847491542'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1453578986847491542'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/08/checking-if-integer-is-power-of-2.html' title='Checking if an Integer is a Power of 2'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5584431821541969380</id><published>2010-07-31T06:42:00.007-04:00</published><updated>2010-07-31T20:43:31.341-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Small Comparison Optimization = Big Gains</title><content type='html'>This is a small and pretty well known trick, but its worth mentioning since a lot of high-level coders don't seem to realize it, and it could result in some big speedups.&lt;br /&gt;&lt;br /&gt;Lets take a look at some random code snippet:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    const double len   = 10000;&lt;br /&gt;    const double fract = 1.0/3.0;&lt;br /&gt;    for(double i = 1; i &lt; len; i++) {&lt;br /&gt;    for(double j = 1;        ; j++) {&lt;br /&gt;        if (j/i &lt; fract) {&lt;br /&gt;            cout &lt;&lt; j &lt;&lt; " / " &lt;&lt; i &lt;&lt; endl;&lt;br /&gt;        }&lt;br /&gt;        else break;&lt;br /&gt;    }}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;What this code is doing is printing out all fractions that are less than 1/3, for all denominators less than 10,000.&lt;br /&gt;&lt;br /&gt;Notice anything that we can optimize?&lt;br /&gt;&lt;br /&gt;Well if you take a look at the if-statement, notice we are dividing j by i, and then doing a comparison. But as we should know by now, division is a slow operation.&lt;br /&gt;&lt;br /&gt;On Core 2 Duos, double floating-point division has a 6~38 clock cycle latency (exact latency depends on the operand values), whereas multiplication is only 5 cycles, and add/sub are 3 cycles.&lt;br /&gt;&lt;br /&gt;So it would be nice if we can omit that division from the comparison... oh wait we can!&lt;br /&gt;&lt;br /&gt;Using simple mathematics we can do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;     j/i  &lt; fract      =&gt;&lt;br /&gt;i * (j/i) &lt; fract * i  =&gt;&lt;br /&gt;      j   &lt; fract * i&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now we got the same equation, but we were able to remove the division completely!&lt;br /&gt;So in the worst-case that our division was taking 38 clock cycles, this new optimization is ~7 times faster.&lt;br /&gt;&lt;br /&gt;Now lets see this code in action.&lt;br /&gt;Here is the same problem as above, except we've now increased 'len' to 100,000, and instead of printing out the results, we just count the fractions (this way we're not limited by console-write speed):&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    const double len   = 100000;&lt;br /&gt;    const double fract = 1.0/3.0;&lt;br /&gt;    int ret = 0;&lt;br /&gt;    for(double i = 1; i &lt; len; i++) {&lt;br /&gt;    for(double j = 1;        ; j++) {&lt;br /&gt;        if (j &lt; fract * i) {&lt;br /&gt;            ret++;&lt;br /&gt;        }&lt;br /&gt;        else break;&lt;br /&gt;    }}&lt;br /&gt;    cout &lt;&lt; ret &lt;&lt; endl;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When I ran the above code using "if (j/i &lt; fract)", it took ~19 seconds to finish on my PC.&lt;br /&gt;When I ran the optimized version using "if (j &lt; fract*i), it took ~2 seconds to finish executing! That's an even bigger speedup than predicted.&lt;br /&gt;&lt;br /&gt;I hope this shows why optimization is important.&lt;br /&gt;&lt;br /&gt;One last thing to note:&lt;br /&gt;When using integers, you might not always want to do this trick.&lt;br /&gt;j/i &gt; x, is not necessarily the same as j &gt; x*i when using integers, since the first one truncates the value (obviously, since integers don't hold the fractional part).&lt;br /&gt;For example:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int i = 21;&lt;br /&gt;    int j =  2;&lt;br /&gt;&lt;br /&gt;    if (i/j &gt; 10) cout &lt;&lt; "First one"  &lt;&lt; endl;&lt;br /&gt;    if (i &gt; 10*j) cout &lt;&lt; "Second one" &lt;&lt; endl;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above example only prints out "Second one" since we're using integers (if i and j were doubles, it would print out "First one" and "Second one").&lt;br /&gt;&lt;br /&gt;This isn't really a negative, since when using integers you probably want to be using the second-method anyways, so you don't have to deal with converting to floats; in that case, you not only would save time by not doing a division, but you would also save time by not doing an int-to-float conversion.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5584431821541969380?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5584431821541969380/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/small-tip.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5584431821541969380'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5584431821541969380'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/small-tip.html' title='Small Comparison Optimization = Big Gains'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6960383208158178459</id><published>2010-07-21T20:13:00.008-04:00</published><updated>2010-07-31T20:07:58.919-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='recursion'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Recursion is not always good!</title><content type='html'>In my university's computer science curriculum, they seem to put a big emphasis in using recursion to solve things, as opposed to alternative methods (such as loops).&lt;br /&gt;&lt;br /&gt;It is indeed true that recursion can simplify the high-level code, and many times it can look beautiful. There is of-course a price to pay with recursion, and that is the extra overhead recursive calls have (therefor they're usually slower than alternative iterative/loop versions).&lt;br /&gt;&lt;br /&gt;I will stress that learning to think recursively is indeed a good skill to have, and any good programmer should be able to do so. So in that sense, it is good that computer science curriculums seem to be stressing recursion; however, once you have learned to think recursively, it is again beneficial to start thinking non-recursively when algorithms are simple-enough to do so.&lt;br /&gt;&lt;br /&gt;Let's consider one of the most common examples of recursion used, the factorial function! (I have used this function many times in my previous articles to demonstrate things, so shouldn't be a surprise :D)&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;T factorial(T n) {&lt;br /&gt;    return n &lt;= 1 ? 1 : n * factorial(n-1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int n = factorial(5);&lt;br /&gt;    cout &lt;&lt; n &lt;&lt; endl; // Prints "120"&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This does end up looking pretty clean, as we can do the whole factorial function in one line.&lt;br /&gt;&lt;br /&gt;Now lets take a look at the iterative/loop version:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;template&amp;lt;typename T&amp;gt;&lt;br /&gt;T factorial(T n) {&lt;br /&gt;    T ret = n ? n :(n=1);&lt;br /&gt;    while(--n) ret*=n;&lt;br /&gt;    return ret;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int n = factorial(5);&lt;br /&gt;    cout &lt;&lt; n &lt;&lt; endl; // Prints "120"&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now this iterative version is not as 'beautiful' as the recursive version, because as you can see its 3 lines instead of 1.&lt;br /&gt;&lt;br /&gt;However the generated code for this version ends up being nicer than the recursive version.&lt;br /&gt;&lt;br /&gt;When you make recursive calls, the arguments that are passed to the recursive function need to be pushed on the stack, and then these arguments eventually need to be popped back out as well. Furthermore, not only do the arguments need to be pushed on the stack, but also the return address needs to be pushed. Sometimes the recursion can be nested so-deep, that you end up running out of stack, and get a stack-overflow crash. This extra overhead is the downside of recursion.&lt;br /&gt;&lt;br /&gt;The iterative/loop version doesn't have such problems. No function calls are made so you don't have the function call overhead. Instead the loop versions usually end up compiling with a simple short-jump.&lt;br /&gt;&lt;br /&gt;Another thing is that the loop version is inline-able, whereas the recursive version likely will not be inlined, and even if it does get inlined, it probably will only inline the first call to the function.&lt;br /&gt;&lt;br /&gt;Potentially the compiler might be able to turn a recursive call into a iterative/loop-version, but don't count on this. At least, I haven't seen it happen...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now, there are some cases where an algorithm will end up being naturally-recursive, and it ends up being difficult or unpractical to code an iterative version. In these cases recursion is the better way to go (in these cases, the algorithm can end up being faster using recursion instead of iteration as well). So in the end, it really depends on the situation whether to go with recursion or iteration/loops; the more experience you get, the more you figure out when to use recursion vs iteration.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;If you noticed, I was using template-functions for the factorial function. The reason I made it a template, is because the factorial function is something you may want to re-use with different data-types (int, unsigned int, long long int, float, double, some custom BigInteger class, etc...).&lt;br /&gt;Using templates, we only have to code one function that can be reused by these different data-types.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6960383208158178459?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6960383208158178459/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/recursion-is-not-always-good.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6960383208158178459'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6960383208158178459'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/recursion-is-not-always-good.html' title='Recursion is not always good!'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-1507157508563011238</id><published>2010-07-19T03:52:00.010-04:00</published><updated>2010-07-20T15:48:54.569-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Max/Min Values for Signed and Unsigned Ints</title><content type='html'>There are a variety of ways you can assign the max/min values to a signed/unsigned integer.&lt;br /&gt;&lt;br /&gt;A very professional looking way is using the numeric_limits class like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#include &amp;lt;limits&amp;gt;&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int x = numeric_limits&amp;lt;int&amp;gt;::max();&lt;br /&gt;    int y = numeric_limits&amp;lt;int&amp;gt;::min();&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;But there are many other ways you can do this; and they all take a lot less typing than using numeric_limits, and you don't have to include any extra headers...&lt;br /&gt;&lt;br /&gt;Lets first take a look at max/min integer values for different variables (in hexadecimal representation because its easier to memorize):&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// u8, u16, u32... mean unsigned int of 8, 16, and 32 bits respectively&lt;br /&gt;// s8, s16, s32... mean   signed int of 8, 16, and 32 bits respectively&lt;br /&gt;----------------------------------&lt;br /&gt;| type | max        | min        |&lt;br /&gt;----------------------------------&lt;br /&gt;| u8   | 0xff       | 0x0        |&lt;br /&gt;| u16  | 0xffff     | 0x0        |&lt;br /&gt;| u32  | 0xffffffff | 0x0        |&lt;br /&gt;----------------------------------&lt;br /&gt;| s8   | 0x7f       | 0x80       |&lt;br /&gt;| s16  | 0x7fff     | 0x8000     |&lt;br /&gt;| s32  | 0x7fffffff | 0x80000000 |&lt;br /&gt;----------------------------------&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The table is pretty easy to memorize. Essentially, for unsigned ints, the max value is always a bunch of f's in hexadecimal, and the min-value is always 0.&lt;br /&gt;For signed ints, the max value is always 0x7f, followed by a bunch of f's.&lt;br /&gt;And lastly the min value for signed ints is always 0x80, followed by a bunch of 0's.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;One thing to notice is the bitwise representation for "-1" always has all-bits set.&lt;br /&gt;That means that for a 32bit integer, "-1" is "0xffffffff", which is the max value for an unsigned integer.&lt;br /&gt;&lt;br /&gt;This means that for unsigned integers, we can declare int max/min like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    unsigned int x = -1u; // Unsigned int max&lt;br /&gt;    unsigned int y = 0;   // Unsigned int min&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In c++, you can put the suffix "u" at the end of an int literal to mean its unsigned. So what that code is doing, is treating the value "-1" as an unsigned int, which means its assigning 0xffffffff to the variable 'x'.&lt;br /&gt;&lt;br /&gt;Here's the thing, I've noticed that some compilers end up generating warnings when you treat a negative number as unsigned in operations, so instead of writing '-1u', we can notice that negative one, is really the same as NOT 0, so we can instead write '~0u'. This will do the same thing, and is generally better to do since it won't generate the compiler errors.&lt;br /&gt;&lt;br /&gt;So its nicer to do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    unsigned int x = ~0u; // Unsigned int max&lt;br /&gt;    unsigned int y = 0;   // Unsigned int min&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now that we know this trick for unsigned ints, lets think of signed integers.&lt;br /&gt;The max value for 32bit signed integers is 0x7fffffff.&lt;br /&gt;If we notice though, 0x7fffffff is really (0xffffffff &gt;&gt; 1).&lt;br /&gt;That is, signed int max, is equal to unsigned int max shifted right by one.&lt;br /&gt;But since we already learned the trick on how to represent unsigned int max easily, we can use that to our advantage:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int x = ~0u&gt;&gt;1; // Signed int max&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The last thing to notice for signed ints, is that the minimum value for 32bit signed ints in hex is 0x80000000, but it just so happens that that number is signed int max + 1, that is 0x7fffffff + 1.&lt;br /&gt;&lt;br /&gt;So we can end up doing this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int x = ~0u&gt;&gt;1;    // Signed int max&lt;br /&gt;    int y =(~0u&gt;&gt;1)+1; // Signed int min&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That about does it for integers, for floats its not as simple so I didn't talk about them here. Maybe I'll end up making another blog post about the different floating point representations...&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;When doing the '-1' or '~0' tricks where you shift the value; be sure to do the shift as an unsigned operation! That is either do: ~0u&gt;&gt;1 or (unsigned int)~0&gt;&gt;1, DO NOT do ~0&gt;&gt;1. This will do an arithmetic shift, instead of a logical shift, and make the result be -1, instead of 0x7fffffff.&lt;br /&gt;&lt;br /&gt;And in-case you're wondering, these tricks are not 'slower' than typing in the numbers manually. C++ compilers do something called constant-propagation and constant-folding, which converts stuff like (-1u&gt;&gt;1)+1 to a constant at compile-time, and therefore there's no extra overhead compared to typing 0x80000000....&lt;br /&gt;&lt;br /&gt;Also, this will not apply to most people, but another thing to note is that some very-old/weird hardware can use one's complement integers (instead of two's complement) or some other funky stuff; when dealing with weird hardware its best to use the numeric_limits class instead of bitwise tricks, because numeric_limits assigns its values based on the specific platform. That-said, I don't even know any hardware that uses one's complement for signed integers, so these tricks are almost always safe :p&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-1507157508563011238?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/1507157508563011238/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/maxmin-values-for-signed-and-unsigned.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1507157508563011238'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1507157508563011238'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/maxmin-values-for-signed-and-unsigned.html' title='Max/Min Values for Signed and Unsigned Ints'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2876449106624855104</id><published>2010-07-15T06:08:00.004-04:00</published><updated>2010-07-15T06:26:19.226-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++0x'/><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>C++0x reusing same keywords and symbols for entirely different meanings</title><content type='html'>One thing especially bad about c++0x is that it seems to give different meanings to already known keywords and symbols.&lt;br /&gt;&lt;br /&gt;For example, the array subscript operator "[]", already can be used to define arrays and index them, but now in c++0x they also denote lambda expressions.&lt;br /&gt;&lt;br /&gt;But an even more ludicrous example is the keyword "auto".&lt;br /&gt;&lt;br /&gt;"auto" in c++0x can be used to infer the type of an identifier, but it just so happens that "auto" already has a meaning in c++.&lt;br /&gt;&lt;br /&gt;auto is used to denote "automatic storage", which essentially means stack-storage for variables that weren't declared globally..&lt;br /&gt;So you can do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;auto int i = 0;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The reason you don't ever see code explicitly using auto, is because 'auto' is on by default, so its rarely used.&lt;br /&gt;&lt;br /&gt;This means however, that in a c++0x function you should be able to do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;auto auto i = 0;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I tested this with GCC 4.5.0, and got a compiler error :/&lt;br /&gt;In fact, GCC 4.5.0 with c++0x extensions enabled doesn't even compile "auto int i = 0;"...&lt;br /&gt;&lt;br /&gt;I think this is a GCC bug, but still this shows the problems that reusing keywords and symbols can cause.&lt;br /&gt;&lt;br /&gt;Also, needless to say, it makes things a lot more confusing for beginners to understand the different meanings of the words...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2876449106624855104?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2876449106624855104/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/c0x-reusing-same-keywords-and-symbols.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2876449106624855104'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2876449106624855104'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/c0x-reusing-same-keywords-and-symbols.html' title='C++0x reusing same keywords and symbols for entirely different meanings'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-8731145067841747570</id><published>2010-07-14T18:13:00.002-04:00</published><updated>2010-07-14T18:16:32.058-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>String Literal with Array Subscript Trick</title><content type='html'>This is a cool trick I just found out recently.&lt;br /&gt;&lt;br /&gt;If you have a string literal such as "abcdef", you can interpret that as an array and use the '[]' operator to get the correct character from the string.&lt;br /&gt;&lt;br /&gt;For example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    for (int i = 9; i &gt;= 0; i--) {&lt;br /&gt;        cout &lt;&lt; "abcdefghij"[i];&lt;br /&gt;    }&lt;br /&gt;    cout &lt;&lt; endl;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That will print out "jihgfedcba".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now knowing this trick (as well as some other minor changes), we can omit a few lines from our hexToString() function in my &lt;a href = http://cottonvibes.blogspot.com/2010/07/random-string-functions.html&gt;previous article&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;string toHexString(u32 value) {&lt;br /&gt;    char str9[9] = {'0'}; // '0' char followed by null bytes&lt;br /&gt;    for (int i = 7, pos = 0; i &gt;= 0; i--) {&lt;br /&gt;        char dig = (value&gt;&gt;(i*4))&amp;0xf;&lt;br /&gt;        if (!dig &amp;&amp; !pos) continue;&lt;br /&gt;        str9[pos++] = "0123456789abcdef"[dig];&lt;br /&gt;    }&lt;br /&gt;    return string(str9);&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-8731145067841747570?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/8731145067841747570/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/string-literal-with-array-subscript.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8731145067841747570'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/8731145067841747570'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/string-literal-with-array-subscript.html' title='String Literal with Array Subscript Trick'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4305625556657951965</id><published>2010-07-14T02:56:00.008-04:00</published><updated>2011-09-29T03:06:12.491-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Multi-Dimensional Array Optimization</title><content type='html'>When using multidimensional arrays in c++ (or most languages for that matter), it is better to use powers of 2 for all dimensions (except for the first one which doesn't matter).&lt;br /&gt;&lt;br /&gt;For example, take the following multi-dimensional array:&lt;br /&gt;int a[3][3][3];&lt;br /&gt;&lt;br /&gt;It will be faster to reference the elements in the following array instead:&lt;br /&gt;int a[3][4][4];&lt;br /&gt;&lt;br /&gt;The reason is that the compiler can use shifts when calculating the address to read from, as opposed to using multiplication operations. On x86 processors, this shifting by powers of 2 could even be implicit as part of the memory addressing modes which allow a shift parameter in their encoding.&lt;br /&gt;&lt;br /&gt;So if you need speed, it could be beneficial to use powers of 2 dimensions even when you don't actually reference the extra memory. Although this optimization may require benchmarking if you increase the size of the array with too much unused data; because it may slow down the code by having less efficient cache-usage due to the extra unused memory. (in the case where all the memory will be used, then its a win-win situation)&lt;br /&gt;&lt;br /&gt;In some cases you don't even need to increase the array dimensions to benefit from this knowledge. If you have an array "int arr[4][7];" you know it will be more efficient to swap the dimensions and just access it the other way: "int arr[7][4]".&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4305625556657951965?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4305625556657951965/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/multi-dimensional-array-optimization.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4305625556657951965'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4305625556657951965'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/multi-dimensional-array-optimization.html' title='Multi-Dimensional Array Optimization'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5388820779439507846</id><published>2010-07-14T01:21:00.007-04:00</published><updated>2010-09-12T21:59:05.656-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='hex'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Reading Hexadecimal Numbers and Understanding Binary Numbers</title><content type='html'>This post is aimed towards beginners trying to understand hexadecimal numbers, and why programmers often use them instead of base-10 decimal.&lt;br /&gt;&lt;br /&gt;Well computers internally deal with logic circuits and we have a concept of a 'bit', which represents either '1' or '0', 'on' or 'off', etc...&lt;br /&gt;&lt;br /&gt;You can put 8 bits together and form a byte. These 8 bits can then be interpreted as a binary string to represent a number.&lt;br /&gt;The first bit, called the least-significant bit, represents 2^0 power (0 or 1).&lt;br /&gt;The second bit, represents 2^1 power (0 or 2)&lt;br /&gt;The third bit, represents 2^2 power (0 or 4), etc...&lt;br /&gt;&lt;br /&gt;So in one byte, you have 8-bits that represent this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt; b7,  b6,  b5,  b4,  b3,  b2,  b1,  b0&lt;br /&gt;2^7, 2^6, 2^5, 2^4, 2^3, 2^2, 2^1, 2^0&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All these bit-values are then added together to give you the value of the number.&lt;br /&gt;&lt;br /&gt;For example, '4' is represented as "00000100", notice that b2 is set (2^2)&lt;br /&gt;Likewise, '5' is "00000101", notice that b2 and b0 are set (2^2 + 2^0 == 4 + 1 == 5)&lt;br /&gt;And so on...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now because internally numbers are represented in this format, you should understand that binary numbers are pretty important to programmers, especially low-level programmers.&lt;br /&gt;&lt;br /&gt;But notice that it takes 8 digits to represent 1-byte, a byte only represents 1-char in c++.&lt;br /&gt;But usually we deal with ints, these don't just represent 1-byte, but instead 4-bytes (usually).&lt;br /&gt;&lt;br /&gt;That means it will take 8*4 = 32 digits to represent an integer in binary!&lt;br /&gt;You can't expect a programmer to be writing 32-digit numbers full of 1's and 0's. There has to be a better way!&lt;br /&gt;&lt;br /&gt;That's where hexadecimal comes in.&lt;br /&gt;It just so happens that 1-digit in hexadecimal, represents exactly 4-digits in binary. This is very useful to us, because that means if we memorize the hexadecimal digits, then we can easily refer to 4-binary digits with just 1 hexadecimal digit.&lt;br /&gt;&lt;br /&gt;The 16 digits in hexadecimal are:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt; Hex | Binary&lt;br /&gt;--------------&lt;br /&gt;  0  | 0000&lt;br /&gt;  1  | 0001&lt;br /&gt;  2  | 0010&lt;br /&gt;  3  | 0011&lt;br /&gt;  4  | 0100&lt;br /&gt;  5  | 0101&lt;br /&gt;  6  | 0110&lt;br /&gt;  7  | 0111&lt;br /&gt;  8  | 1000&lt;br /&gt;  9  | 1001&lt;br /&gt;  a  | 1010&lt;br /&gt;  b  | 1011&lt;br /&gt;  c  | 1100&lt;br /&gt;  d  | 1101&lt;br /&gt;  e  | 1110&lt;br /&gt;  f  | 1111&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The key to using hexadecimal fluently, is memorizing this hex-to-binary table.&lt;br /&gt;I'll give you some hints to remember some of the numbers:&lt;br /&gt;0 is 0 in hex and in binary.&lt;br /&gt;1 is 1 in hex and in binary.&lt;br /&gt;1, 2, 4, and 8 only have 1-bit set (because they're powers of 2)&lt;br /&gt;f is the last hex number, and has all 4-bits set (all 1's)&lt;br /&gt;'a' comes after 9, which in decimal should be '10', if you notice though, 'a' represents '1010' in binary, so think of two 10's.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Anyways, it takes some time to memorize the table, but once you do, you are then able to convert hex numbers to binary very easily.&lt;br /&gt;For example:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;           7      f&lt;br /&gt;0x7f = | 0111 | 1111 |&lt;br /&gt;&lt;br /&gt;           5      5&lt;br /&gt;0x55 = | 0101 | 0101 |&lt;br /&gt;&lt;br /&gt;                 a      b      c      d      e      f      9      8&lt;br /&gt;0xabcdef98 = | 1010 | 1011 | 1100 | 1101 | 1110 | 1111 | 1001 | 1000 |&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;As you can see by the last example, we were able to represent a 32-bit number with just 8 digits. Instead of typing "10101011110011011110111110011000" we just had to type "0xabcdef98".&lt;br /&gt;&lt;br /&gt;Oh and just so you know, c++ uses the prefix "0x" to refer to hexadecimal numbers.&lt;br /&gt;Sometimes people use "$" to refer to hex, or sometimes they just use "x" as the prefix.&lt;br /&gt;&lt;br /&gt;Also I should note that the reason you can't use normal base-10 decimal numbers to refer to binary easily, is because a single decimal digit does not equal an exact amount of binary digits. 3-binary digits is octal, and 4-binary digits is hex. Decimal is in-between those, so you can't use decimal to refer to binary numbers nicely.&lt;br /&gt;&lt;br /&gt;Anyways I hope this article helps those who were having a bit of trouble understanding hex.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5388820779439507846?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5388820779439507846/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/reading-hexadecimal-numbers-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5388820779439507846'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5388820779439507846'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/reading-hexadecimal-numbers-and.html' title='Reading Hexadecimal Numbers and Understanding Binary Numbers'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-247407059344836091</id><published>2010-07-12T20:14:00.010-04:00</published><updated>2010-07-14T02:40:58.421-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Random String Function Implementations</title><content type='html'>There are a bunch of string functions out-there that do almost everything you could want to do with strings.&lt;br /&gt;&lt;br /&gt;There's so much however that sometimes its just simpler to implement your own method instead of finding the appropriate function to use.&lt;br /&gt;&lt;br /&gt;What if you wanted to find the size of a char-array string including its NULL-byte.&lt;br /&gt;Well you can easily and elegantly do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int strSize(const char* str) {&lt;br /&gt;    int len = 0;&lt;br /&gt;    while(str[len++]);&lt;br /&gt;    return len;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Another easy thing to implement is a toLower() function which converts uppercase letters to lowercase:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;void strToLower(char* str) {&lt;br /&gt;    for( ; *str; str++) {&lt;br /&gt;        char&amp; c = *str;&lt;br /&gt;        if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') c = c - 'A' + 'a';&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;A matching toUpper() function is obviously just as easy ;p&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Last here's a fun function I made that converts a 'u32' (unsigned 32-bit integer), to a hex string:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;string toHexString(u32 value) {&lt;br /&gt;    char str9[9];&lt;br /&gt;    u32  pos = 0;&lt;br /&gt;    for (int i = 0; i &lt; 8; i++) {&lt;br /&gt;        char dig = (value&gt;&gt;((7-i)*4))&amp;0xf;&lt;br /&gt;        if (!dig &amp;&amp; !pos) continue;&lt;br /&gt;        if ((dig) &lt;  0xa) str9[pos] = '0' + dig;&lt;br /&gt;        else              str9[pos] = 'a' +(dig-0xa);&lt;br /&gt;        pos++;&lt;br /&gt;    }&lt;br /&gt;    if (!pos) { str9[0] = '0'; pos=1; } &lt;br /&gt;    str9[pos] = '\0';&lt;br /&gt;    return string(str9);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That one is definitely more complex than the others, but it was fun to code.&lt;br /&gt;All hex digits are 4-bits, and a u32 value only needs a char array of at-most size 9 (8 digits + 1 null byte).&lt;br /&gt;&lt;br /&gt;Anyways, in real coding projects its probably best to use already defined functions that perform the string operation you want; but implementing your own can sometimes be fun, and possibly impress your professors on homework assignments.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-247407059344836091?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/247407059344836091/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/random-string-functions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/247407059344836091'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/247407059344836091'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/random-string-functions.html' title='Random String Function Implementations'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2556777073033321982</id><published>2010-07-12T05:43:00.009-04:00</published><updated>2010-07-12T16:21:09.562-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Nested Functions in C++</title><content type='html'>Although c++ does not natively support nested functions, you can do a trick to support them using structs/classes.&lt;br /&gt;&lt;br /&gt;In my other blog post I talked about how lambdas can be used as nested functions, and I also showed a way to do recursion with lambdas. If you have access to c++0x, then the nicer way to do nested functions is using lambdas, but if you don't, then you can use the nested-class trick.&lt;br /&gt;&lt;br /&gt;Although it may sound odd, you can declare a struct/class in a function. And then this struct/class can have a static method which you can call.&lt;br /&gt;&lt;br /&gt;Here's one version of it:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    struct factClass {&lt;br /&gt;        static int factorial(int x) {&lt;br /&gt;            return (x &lt;= 1) ? 1 : x * factorial(x-1);&lt;br /&gt;        }&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; factClass::factorial(5) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Okay real quickly I want to point out that in c++, structs and classes are the same thing; the only difference is the default access between structs and classes.&lt;br /&gt;&lt;br /&gt;With struct all the method/variables are 'public' by default, and with classes they're 'private' by default.&lt;br /&gt;You can change the behavior by specifying "public:" or "protected:" or "private:" keywords for both structs and classes.&lt;br /&gt;When I first started with c++ I didn't know this, so that's why I'm mentioning it :D&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Okay now that I got that out of the way, as you can see the above function is pretty bloated.&lt;br /&gt;We can use macros to hide some of the bloat of the class declaration like so:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#define nested(className) struct className { static&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    nested(factClass) int factorial(int x) {&lt;br /&gt;        return (x &lt;= 1) ? 1 : x * factorial(x-1);&lt;br /&gt;    }};&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; factClass::factorial(5) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There's also another way to do this using functors.&lt;br /&gt;Basically what we do is have a struct/class and then overload its "()" operator to make it look like a function call like so:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    struct {&lt;br /&gt;        int operator()(int x) {&lt;br /&gt;            return (x &lt;= 1) ? 1 : x * this-&gt;operator()(x-1);&lt;br /&gt;        }&lt;br /&gt;    } factorial;&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; factorial(5) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now that's pretty cool.&lt;br /&gt;We create an anonymous struct, and 'factorial' is an instance of that struct. Then it has the overloaded '()' operator which lets us call factorial(5) as if it was a function.&lt;br /&gt;&lt;br /&gt;We can again use macros to hide some of the bloat, although the end result looks kind-of weird:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#define nested(xReturnType) struct { xReturnType operator()&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;    nested(int)(int x) {&lt;br /&gt;        return (x &lt;= 1) ? 1 : x * this-&gt;operator()(x-1);&lt;br /&gt;    }} factorial;&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; factorial(5) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The nice thing about using functors like in the last two examples is that you don't have to use a separate class name and function name (className::functionName()), instead you just use one name and call it with that name. &lt;br /&gt;&lt;br /&gt;Anyways there you go, we have shown a variety of ways you can do nested functions, and I would stick to lambdas unless you're not using c++0x, in which you'll have to use one of the nested-class tricks mentioned above ;p&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2556777073033321982?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2556777073033321982/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/nested-functions-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2556777073033321982'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2556777073033321982'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/nested-functions-in-c.html' title='Nested Functions in C++'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5580287319999244322</id><published>2010-07-12T02:29:00.025-04:00</published><updated>2011-01-06T12:16:24.289-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++0x'/><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='recursion'/><category scheme='http://www.blogger.com/atom/ns#' term='lamdas'/><category scheme='http://www.blogger.com/atom/ns#' term='hacks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>c++0x autos, lambdas, and lambda recursion!</title><content type='html'>C++0x introduces some new features that will probably end up making C++0x code many-times more obfuscated and harder to read; however the features can be very useful and fun to code with as well.&lt;br /&gt;&lt;br /&gt;The first interesting feature I'll talk about is the "auto" keyword. Essentially you can use the auto keyword to hold a type that will be automatically inferred.&lt;br /&gt;For example:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int  a = 1;    // Type is explicitly int&lt;br /&gt;auto b = 1;    // Type of 'int', which is inferred by the int literal&lt;br /&gt;auto c = a;    // Type of 'int', which is inferred by the type of a&lt;br /&gt;auto d = 1.4f; // Type of 'float', which is inferred by the float literal&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The auto keyword will probably be abused by c++0x coders, making code harder to follow; I imagine people will start using this for a-lot of their variable declarations, making it difficult to know the true types of variables when browsing code.&lt;br /&gt;&lt;br /&gt;The auto keyword has some great uses, but I will not explicitly talk about them here because it'll make this post too long...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The second feature I'll talk about are lambdas.&lt;br /&gt;When I first saw the c++0x lambdas I thought it looked very confusing, but after playing around with them I found out they're pretty fun.&lt;br /&gt;&lt;br /&gt;I'll use &lt;a href="http://msdn.microsoft.com/en-us/library/bb531253.aspx"&gt;Microsoft's definition&lt;/a&gt; of lambda expression:&lt;br /&gt;"A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression."&lt;br /&gt;&lt;br /&gt;Basically a lambda allows you to create anonymous functions, and they can be defined within other c++ functions, so it also allows you to do nested functions.&lt;br /&gt;&lt;br /&gt;They look like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Foo is a function pointer to a lambda that has nothing in its body,&lt;br /&gt;// so it does nothing...&lt;br /&gt;auto foo = [](){};&lt;br /&gt;&lt;br /&gt;// [] tells which variables in the current scope will be available to the lambda&lt;br /&gt;// () is the parameter list to be passed to the lambda function&lt;br /&gt;// {} is the lambda's body&lt;br /&gt;&lt;br /&gt;// You can now call foo like so:&lt;br /&gt;foo();&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Okay I know this is confusing, so I'll give a concrete example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    auto foo = [](int x) { return x * x; };&lt;br /&gt;    cout &lt;&lt; foo(2) &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That prints out '4' to console.&lt;br /&gt;As you can see we have a parameter list of "int x", and then in the body of the lambda we are returning x*x.&lt;br /&gt;Notice how you don't have to explicitly mention a return-type! That is also an interesting feature of c++0x.&lt;br /&gt;&lt;br /&gt;Now the '[]' part of the lambda is a bit tricky to understand, basically it allows you to specify variables from the current scope that will be available to the lambda's body.&lt;br /&gt;&lt;br /&gt;For example you can do this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int x = 2;&lt;br /&gt;    auto foo = [&amp;amp;x]() { return x * x; };&lt;br /&gt;    cout &lt;&lt; foo(2) &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This will return '4'.&lt;br /&gt;What its saying is that the lambda's body has access to the 'x' from the main() function.&lt;br /&gt;If you modify 'x' in the lambda's body, the 'x' in the main() function will also be modified because we're passing the value by reference.&lt;br /&gt;If you want to pass x by value, you can just omit the ampersand, and it will pass the variable by value.&lt;br /&gt;&lt;br /&gt;If you want the lambda to have access to all local variables then you can do:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    int x = 2;&lt;br /&gt;    auto foo = [&amp;amp;]() { return x * x; };&lt;br /&gt;    cout &lt;&lt; foo(2) &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Using the '[&amp;amp;]' means that you're passing all variables of the same scope by reference.&lt;br /&gt;You can also use '[=]' which means you're passing them all by value.&lt;br /&gt;You can even do something like, '[&amp;amp;, x]', which means you're passing all by reference, except for 'x' which will be passed by value.&lt;br /&gt;&lt;br /&gt;Technically I've been assigning an identifier to the lambda 'foo', so I've not been using lambdas as anonymous functions here.&lt;br /&gt;&lt;br /&gt;The way you would use lambdas as anonymous functions (a function without a name or identifier), is when another method takes a function object as an argument.&lt;br /&gt;The typical example seen all over the web is with 'for_each'.&lt;br /&gt;The arguments for for_each() are &lt;a href="http://msdn.microsoft.com/en-us/library/e5sk9w9k.aspx"&gt;found here&lt;/a&gt;, but basically are:&lt;br /&gt;param1 = A starting iterator&lt;br /&gt;param2 = An ending iterator&lt;br /&gt;param3 = A function Object&lt;br /&gt;&lt;br /&gt;So you can either pass an already defined function as param3, or you can use lambdas to define the function in the current scope.&lt;br /&gt;&lt;br /&gt;This example is on &lt;a href="http://msdn.microsoft.com/en-us/library/e5sk9w9k.aspx"&gt;wikipedia&lt;/a&gt;, but I'll reuse it here.&lt;br /&gt;Suppose you have a vector full of ints, and you want to add up all the ints together.&lt;br /&gt;With for_each, you can specify a lambda as param3 which adds each int to a 'total' variable:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;std::vector&amp;lt;int&amp;gt; someList;&lt;br /&gt;int total = 0;&lt;br /&gt;std::for_each(someList.begin(), someList.end(), [&amp;amp;](int x) {&lt;br /&gt;    total += x;&lt;br /&gt;});&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I recommend reading the wikipedia link as it has more examples.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Finally the last thing I want to mention is lambda recursion.&lt;br /&gt;When I originally tried using recursion with c++ lambdas, I got compiler errors. So I ended up concluding that recursive lambdas in c++ were not possible without using hacks.&lt;br /&gt;&lt;br /&gt;I ended up coding a hack to support lambda recursion:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;typedef int(*pFoo)(int, int);&lt;br /&gt;&lt;br /&gt;int main() {&lt;br /&gt;&lt;br /&gt;    pFoo foo = [](int x, int _f) -&gt; int { &lt;br /&gt;        int*  _p = (int*)&amp;_f;&lt;br /&gt;        void*&amp; p = (void*&amp;)*_p;&lt;br /&gt;        pFoo*  a = (pFoo*)_p;&lt;br /&gt;        pFoo   f = *a;&lt;br /&gt;        return (x&lt;=1) ? 1 : x * f(x-1, _f);&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    int* _p = (int*)&amp;foo;&lt;br /&gt;    int   p = *_p;&lt;br /&gt;&lt;br /&gt;    cout &lt;&lt; foo(5, p) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Yes I know its super ugly, I had to do a lot of ugly casts to get GCC to compile without warnings or errors.&lt;br /&gt;&lt;br /&gt;The basic idea here is that you define the lambda taking two arguments, one being the integer we will perform the factorial function on, and the other being a function pointer to the lambda itself. The lambda can then use that function pointer to call itself. The function pointer in this case is disguised as an 'int', and then casted to the function pointer type.&lt;br /&gt;&lt;br /&gt;I have recently figured out however that you don't need to resort to hacks for lambda recursion!&lt;br /&gt;&lt;br /&gt;Here is the proper way to do lambda recursion:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int main() {&lt;br /&gt;    function&amp;lt;int(int)&amp;gt; factorial = [&amp;factorial](int n) -&gt; int { &lt;br /&gt;        return n &lt;= 1 ? 1 : n * factorial(n-1);&lt;br /&gt;    };&lt;br /&gt;    cout &lt;&lt; factorial(5) &lt;&lt; endl; // Prints '120'&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Notice how we give the lambda access to the 'factorial' variable.&lt;br /&gt;&lt;br /&gt;I had tried this before using 'auto' instead of 'function&amp;lt;int(int)&amp;gt;' and it didn't work with GCC, so I had assumed recursive lambdas were not supported (I had also read posts by people saying they weren't supported... guess they were wrong :p).&lt;br /&gt;&lt;br /&gt;So the trick is to not use 'auto' when declaring the lambda type, but instead use function&amp;lt;int(int)&amp;gt; to explicitly show its a function.&lt;br /&gt;&lt;br /&gt;And when you think about it, it makes sense that you can't use 'auto' when using lambda recursion, since you're using the identifier before its type has fully been defined.&lt;br /&gt;&lt;br /&gt;Anyways, with the introduction of lambdas, c++0x has nice support for nested functions, recursive nested functions, and anonymous functions.&lt;br /&gt;&lt;br /&gt;So get yourself a c++0x compiler and try it out!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5580287319999244322?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5580287319999244322/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/c0x-autos-lambdas-and-lambda-recursion.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5580287319999244322'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5580287319999244322'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/c0x-autos-lambdas-and-lambda-recursion.html' title='c++0x autos, lambdas, and lambda recursion!'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5604210844611461891</id><published>2010-07-11T02:29:00.004-04:00</published><updated>2010-07-12T02:32:41.404-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Using c++ references for nicer code</title><content type='html'>It is common to see castings and conversions between different types of primitives in c++ code.&lt;br /&gt;Many times however you don't want to do any conversion of the value, but instead just want to reference the binary representation of the variable as another type.&lt;br /&gt;&lt;br /&gt;The common ugly way to do this is something like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Program Entry Point&lt;br /&gt;int main() {&lt;br /&gt;&lt;br /&gt;    // Make x hold the binary representation of a &lt;br /&gt;    // positive infinity float&lt;br /&gt;    int x = 0x7f800000;&lt;br /&gt;&lt;br /&gt;    // Treat x as if it was holding a float instead of an int,&lt;br /&gt;    // and then give f the same value&lt;br /&gt;    float f = *(float*)&amp;x;&lt;br /&gt;&lt;br /&gt;    // Print float f (positive infinity) to the console&lt;br /&gt;    cout &lt;&lt; f &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This does work, however as you can see the second line of code is pretty ugly.&lt;br /&gt;The reason you can't just do "float f = (float)x;", is because that would mean you're casting the int value to a float; so the value is actually converted to a floating point value.&lt;br /&gt;&lt;br /&gt;But that's not what we wanted, we instead want the 'int x' to behave as it was a float the entire time; that is why we first take the address of 'x' (&amp;x), then treat it as a float pointer ((float*)&amp;x), then finally dereference it back (*(float*)&amp;x).&lt;br /&gt;&lt;br /&gt;With c++ however, you can use references to simplify this whole procedure.&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Program Entry Point&lt;br /&gt;int main() {&lt;br /&gt;&lt;br /&gt;    // Make x hold the binary representation of a &lt;br /&gt;    // positive infinity float&lt;br /&gt;    int x = 0x7f800000;&lt;br /&gt;&lt;br /&gt;    // Treat x as if it was holding a float instead of an int,&lt;br /&gt;    // and then give f the same value&lt;br /&gt;    float f = (float&amp;)x;&lt;br /&gt;&lt;br /&gt;    // Print float f (positive infinity) to the console&lt;br /&gt;    cout &lt;&lt; f &lt;&lt; endl;&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This trick was taught to me by Jake Stine from pcsx2, and its something not a lot of coders know apparently, because I commonly see people using the ugly-way to do this instead.&lt;br /&gt;Most-likely because you can't do this in normal C (just another reason why C sucks compared to C++ xD).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5604210844611461891?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5604210844611461891/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/using-c-references-for-nicer-code.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5604210844611461891'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5604210844611461891'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/using-c-references-for-nicer-code.html' title='Using c++ references for nicer code'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-7617369963990578910</id><published>2010-07-11T01:34:00.009-04:00</published><updated>2010-12-19T23:28:09.927-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Fast Multiplication and Division</title><content type='html'>Another well known bitwise trick is that you can do multiplication and division by powers of two "2^n", with just simple shifts by "n".&lt;br /&gt;&lt;br /&gt;For example, you can do:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Multiplication&lt;br /&gt;void mul(int&amp;amp; x) {&lt;br /&gt;   x = x * 4;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Optimized Multiplication&lt;br /&gt;void mul(int&amp;amp; x) {&lt;br /&gt;   x = x &lt;&lt; 2;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And for division:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Division&lt;br /&gt;void div(unsigned int&amp;amp; x) {&lt;br /&gt;   x = x / 4;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Optimized Division&lt;br /&gt;void div(unsigned int&amp;amp; x) {&lt;br /&gt;   x = x &gt;&gt; 2;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Unlike the modulus optimization trick, the multiplication trick &lt;span style="font-weight: bold;"&gt;does&lt;/span&gt; work for both signed and unsigned variables, so the compiler is safe to optimize these cases for you.&lt;br /&gt;&lt;br /&gt;In the case of the division trick there is a problem that may happen if you have a negative signed number. If you divide a negative integer and the result should have a remainder, then using shifts may give you the wrong result (for example, -1/2 should be 0, but -1&gt;&gt;1 is -1).&lt;br /&gt;Compilers are able to optimize signed division by powers of two using shifts and interesting logic to account for the possible errors.&lt;br /&gt;&lt;br /&gt;For the reason that compilers will make the necessary optimizations for you, it is generally better to leave the code as normal multiplications and divisions for readability and to prevent mistakes.&lt;br /&gt;If you're dealing with low level assembly, you'd obviously want to be doing the shifts where possible instead of using mul and div.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-7617369963990578910?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/7617369963990578910/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/fast-multiplication-and-division.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7617369963990578910'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/7617369963990578910'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/fast-multiplication-and-division.html' title='Fast Multiplication and Division'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5291705034376746968</id><published>2010-07-11T00:38:00.006-04:00</published><updated>2010-07-31T20:11:20.234-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Fast Modulus Operation and Using Unsigned Ints as an Optimization</title><content type='html'>This is another pretty well-known trick; but there is often a few misconceptions with it.&lt;br /&gt;&lt;br /&gt;If you are using the modulus operator '%' with a power of 2 value '2^n', then you can do the same operation with a bitwise AND with 2^n-1.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Mod Operation&lt;br /&gt;void mod(unsigned int&amp;amp; x) {&lt;br /&gt;  x = x % 4;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Optimized Mod Operation&lt;br /&gt;void mod(unsigned int&amp;amp; x) {&lt;br /&gt;  x = x &amp;amp; 3;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It is very important to note that this only works with positive/unsigned values.&lt;br /&gt;If x was '-6' for example, the correct value returned should be '-2', but with the optimized mod it would return '2'.&lt;br /&gt;&lt;br /&gt;The optimized mod trick however is very useful as perhaps one of the most common uses of Mod is to check if a number is odd or even:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal isEven Operation&lt;br /&gt;bool isEven(int x) {&lt;br /&gt;  return !(x % 2);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Optimized isEven Operation&lt;br /&gt;void isEven(int x) {&lt;br /&gt;  return !(x &amp;amp; 1);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This works regardless if the input is positive/unsigned, and is &lt;span style="font-weight: bold;"&gt;much&lt;/span&gt; faster than using the modulus operator.&lt;br /&gt;&lt;br /&gt;The way the Modulus operator works in x86-32 is it has to do a Div operation, and get the remainder; Div is almost always a slow operation on any architecture.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I also wanted to point out something else.&lt;br /&gt;The misconception some people have is that the compiler already will optimize something like "x = x % 2" into "x = x &amp;amp; 1", well the real answer is not-always.&lt;br /&gt;&lt;br /&gt;As I already said, the optimization only works for positive/unsigned values, so if you declare x as a normal signed-int, then the compiler can't safely optimize the operation into an AND.&lt;br /&gt;This is why I wanted to point out that using "Unsigned Int" can be an optimization because the compiler will be able to change such mod operations into bitwise ANDs.&lt;br /&gt;&lt;br /&gt;If you leave the values as signed, the compiler either does one of 2 things:&lt;br /&gt;1) Will just compile it using a div and get the remainder.&lt;br /&gt;2) Will compile code that checks the sign bit of value, does the optimized AND, and negates the value if the original value was negative.&lt;br /&gt;&lt;br /&gt;That is, the compiler will do something like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// What the compiler might generate for&lt;br /&gt;// "x = x % 2;" with signed values&lt;br /&gt;if (x &lt; 0) {&lt;br /&gt;    x =  x &amp; 1;&lt;br /&gt;    x = -x;&lt;br /&gt;}&lt;br /&gt;else x = x &amp; 1;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Many times I have seen code where performance has increased dramatically from removing modulus operations in favor of bitwise ANDs or other logic.&lt;br /&gt;&lt;br /&gt;For example, if you were to have a loop like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;for(int i = 0; i &lt; 100000; i++) {&lt;br /&gt;    someVar++;&lt;br /&gt;    someVar%=7;&lt;br /&gt;    // ... Do more stuff&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can make it much faster by doing this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;for(int i = 0; i &lt; 100000; i++) {&lt;br /&gt;    someVar++;&lt;br /&gt;    if (someVar &gt;= 7) someVar = 0;&lt;br /&gt;    // ... Do more stuff&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5291705034376746968?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5291705034376746968/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/fast-modulus-operation-and-using.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5291705034376746968'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5291705034376746968'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/fast-modulus-operation-and-using.html' title='Fast Modulus Operation and Using Unsigned Ints as an Optimization'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6913348253798900276</id><published>2010-07-10T00:08:00.006-04:00</published><updated>2011-10-05T21:54:45.206-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Bitwise Set-Bit</title><content type='html'>Say you want to set a variable to '0' if an integer is 0, and '1' if an integer is non-zero.&lt;br /&gt;&lt;br /&gt;You can do it this way:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int setBit(int x) {&lt;br /&gt;    return !!x;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If you want to instead emulate this behavior, you can do it some other ways.&lt;br /&gt;&lt;br /&gt;If you know for sure the sign-bit is not set, then you can implement this behavior like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int setBit(int x) {&lt;br /&gt;    return (uint)(x + 0x7fffffff) &gt;&gt; 31;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This works because if any bits were set, then it ends up carrying a '1' over to bit #31 (the sign bit).&lt;br /&gt;&lt;br /&gt;If you also want to include the sign bit into this, you can implement the setBit() function like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int setBit(int x) {&lt;br /&gt;    return (((uint)x &gt;&gt; 1) | (x&amp;1)) + 0x7fffffff) &gt;&gt; 31;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Or you can use 64bit operations like this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;int setBit(int x) {&lt;br /&gt;    uint64 y = (uint64)(uint)x + 0xfffffffful;&lt;br /&gt;    return ((int*)&amp;y)[1];&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;This trick isn't really useful when sticking to high level c++, but it can be useful when dealing with low level assembly.&lt;br /&gt;&lt;br /&gt;With x86 if you don't wish to use the SETcc instruction, you can use a variation of the trick for full 32bit detection using the carry bit like so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;    add eax, -1 // Add 0xffffffff to eax&lt;br /&gt;    rcl eax,  1 // Rotate with the carry bit so its in the lsb&lt;br /&gt;    and eax,  1 // AND with the carry bit&lt;/pre&gt;&lt;br /&gt;The above is nice because SETcc only sets the lower byte to 1/0, while this will set the full 32bit register to 1/0. Also because SETcc only modifies the lower byte, it can be a speed penalty with the CPU's pipeline as opposed to modifying the full 32bit register.&lt;br /&gt;&lt;br /&gt;Also note that I use 'int' and 'uint' in this article to refer to 32 bit signed and unsigned ints.&lt;br /&gt;And i use 'uint64' to refer to unsigned 64bit int.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6913348253798900276?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6913348253798900276/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/bitwise-set-bit.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6913348253798900276'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6913348253798900276'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/bitwise-set-bit.html' title='Bitwise Set-Bit'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3123314500616834834</id><published>2010-07-09T22:28:00.004-04:00</published><updated>2010-07-11T02:03:54.259-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Testing for NaN and Infinity values</title><content type='html'>From my work on &lt;a href="http://pcsx2.net/"&gt;pcsx2&lt;/a&gt; I have had to deal extensively with the problem of NaN and Infinity values with floats.&lt;br /&gt;&lt;br /&gt;The ps2's FPU and VU processors do not support NaN or Infinity values, so it is a pain to emulate them on a system that does support such values (x86-32/SSE processors).&lt;br /&gt;&lt;br /&gt;There are a variety of ways to test for NaN and Infinity values, and I will list a few here.&lt;br /&gt;&lt;br /&gt;The first is pretty well known.&lt;br /&gt;If you compare a float for equality against itself, it should return True unless the float is a NaN.&lt;br /&gt;So the typical approach is to do something like:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Test for NaN&lt;br /&gt;bool isNaN(float x) {&lt;br /&gt;    return x != x;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That will only test for NaN's, if you want to check for infinities you can do something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;#include &amp;lt;limits&amp;gt;&lt;br /&gt;#include &amp;lt;math.h&amp;gt;&lt;br /&gt;&lt;br /&gt;// Test for positive or negative infinity values&lt;br /&gt;bool isInf(float x) {&lt;br /&gt;    return fabs(x) == numeric_limits&amp;lt;float&amp;gt;::infinity();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You can instead use bitwise logic to test for NaN's and Infinities.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Test for NaN with bitwise logic&lt;br /&gt;bool isNaN(float x) {&lt;br /&gt;    return ((int&amp;)x &amp; 0x7fffffff) &gt;= 0x7f800001;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Test for Inf with bitwise logic&lt;br /&gt;bool isInf(float x) {&lt;br /&gt;    return ((int&amp;)x &amp; 0x7fffffff) == 0x7f800000;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can even check for both NaN and Infinities with just one comparison:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Test for NaN or Inf with bitwise logic&lt;br /&gt;bool isNaNorInf(float x) {&lt;br /&gt;    return ((int&amp;)x &amp; 0x7fffffff) &gt;= 0x7f800000;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Generally you probably don't want to use the bitwise version of these functions for the reason that the compiled code will end up having to switch from FPU to integer arithmetic, which will most likely end up being slower than sticking to the floating point comparisons.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3123314500616834834?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3123314500616834834/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/testing-for-nan-and-infinity-values.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3123314500616834834'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3123314500616834834'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/testing-for-nan-and-infinity-values.html' title='Testing for NaN and Infinity values'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-1189851128611385425</id><published>2010-07-09T00:15:00.008-04:00</published><updated>2010-07-31T20:12:08.360-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='optimizations'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>Compare Optimization Tricks</title><content type='html'>Okay I invented these bitwise tricks myself, so they shouldn't be as well known as the last one I posted; well the first one is more obvious (so probably other people have used it), but the other one not so much.&lt;br /&gt;&lt;br /&gt;If you're ever comparing an integer being in the range 0...n, you can normally do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Compare&lt;br /&gt;bool compare(int x) {&lt;br /&gt;    return (x &gt;= 0) &amp;&amp; (x &lt;= 10)&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;However, you can do that same operation with just one compare instruction:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Optimized Compare&lt;br /&gt;bool compare(int x) {&lt;br /&gt;    return (unsigned int)x &lt;= 10;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now this second trick is if you want to compare 2 different integers, and want to check if they're both in the range 0...2^n&lt;br /&gt;&lt;br /&gt;Normally you could do this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Compare&lt;br /&gt;bool compare(int x, int y) {&lt;br /&gt;    return (x &gt;= 0) &amp;&amp; (x &lt;= 16)&lt;br /&gt;        &amp;&amp; (y &gt;= 0) &amp;&amp; (y &lt;= 16);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Using the trick mentioned before, we figured out you can optimize it to this:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Optimized Compare&lt;br /&gt;bool compare(int x, int y) {&lt;br /&gt;    return ((unsigned int)x &lt;= 16)&lt;br /&gt;        &amp;&amp; ((unsigned int)y &lt;= 16);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;But now we can further optimize this to just one single compare!&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Very Optimized Compare!&lt;br /&gt;bool compare(int x, int y) {&lt;br /&gt;    return ((unsigned int)(x|y) &lt;= 16);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That ends up doing the work of 4 comparisons, with just 1!&lt;br /&gt;(Although you now have the added OR instruction; but OR is very fast to compute on almost every processor).&lt;br /&gt;&lt;br /&gt;I want to stress again that the last optimization only works when the value is a power of two (2^n).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-1189851128611385425?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/1189851128611385425/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/4-compares-in-1-trick.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1189851128611385425'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1189851128611385425'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/4-compares-in-1-trick.html' title='Compare Optimization Tricks'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5674797630756947309</id><published>2010-07-08T21:54:00.017-04:00</published><updated>2010-07-16T23:24:00.566-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c++'/><category scheme='http://www.blogger.com/atom/ns#' term='bitwise tricks'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='coding'/><title type='text'>xor swap trick and add/sub swap trick</title><content type='html'>This is a pretty common bitwise trick most veteran coders know about, but its probably a good bitwise trick to start this section out with.&lt;br /&gt;&lt;br /&gt;If you have 2 integers, x and y, you can swap their values normally by doing:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Normal Swap Function&lt;br /&gt;_f void swap(int&amp; x, int&amp; y) {&lt;br /&gt;    int c = x;&lt;br /&gt;    x = y;&lt;br /&gt;    y = x;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;But this requires a temporary variable/register to be used (the "int c").&lt;br /&gt;&lt;br /&gt;You can do this same functionality without using a temporary variable at all, using the xor swap trick:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// XOR Swap Function&lt;br /&gt;_f void swap(int&amp; x, int&amp; y) {&lt;br /&gt;    assert(&amp;x != &amp;y);&lt;br /&gt;    x ^= y;&lt;br /&gt;    y ^= x;&lt;br /&gt;    x ^= y;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The result ends up being the same as the first function, but notice now it doesn't use any temporary variables.&lt;br /&gt;This trick can be useful if you're doing some low-level asm work, or reg-alloc in a recompiler, or for any reason you don't have an extra register to spare and your instruction set doesn't have an xchg opcode. Admittingly, if you're just sticking to c++ code, might just be better to use the normal swap routine instead.&lt;br /&gt;&lt;br /&gt;Also beware! This trick has a big problem if &amp;x == &amp;y, that is, if x and y are the same exact variable. In that case instead of keeping the values the same, you end up zeroing out the value!&lt;br /&gt;So the xor swap trick should only be used when you know you are dealing with 2 distinct 'x' and 'y' variables. That is why we put the assert(&amp;x != &amp;y) line in this function, so on debug builds we will get an error if the references of x and y point to the same exact variable.&lt;br /&gt;&lt;br /&gt;Lastly I'll point out that you can do the same trick using add and sub operations, but its a bit messier and not as useful:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Add/Sub Swap Function&lt;br /&gt;_f void swap(int&amp; x, int&amp; y) {&lt;br /&gt;    assert(&amp;x != &amp;y);&lt;br /&gt;    x += y;&lt;br /&gt;    y  = x - y;&lt;br /&gt;    x -= y;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The problem with this code is the second instruction.&lt;br /&gt;For many instruction sets (for example SSE, MMX, or x86-32), you're stuck with "dest, src" syntax for instructions.&lt;br /&gt;This means that the compiled code for this will still end up having to use some type of temporary register or the stack to compute this.&lt;br /&gt;&lt;br /&gt;If you're dealing with another architecture however that has 3-operand syntax "dest, src1, src2", then this is more useful since you can do the second line with just 1 instruction.&lt;br /&gt;&lt;br /&gt;Notes:&lt;br /&gt;&lt;br /&gt;I use "_f" as a macro for "__forceinline" so:&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Forceinline Macro for in-lining functions&lt;br /&gt;#define _f __forceinline&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Also note that this trick can be extended to be used with floats, doubles, and etc...&lt;br /&gt;But you have to be sure to do the operations as 32bit integers or 64bit integers respectively.&lt;br /&gt;&lt;br /&gt;Here's an example of swapping 2 floating point singles with this trick:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: c++"&gt;&lt;br /&gt;// Add/Sub Swap Function&lt;br /&gt;_f void swap(int&amp; x, int&amp; y) {&lt;br /&gt;    assert(&amp;x != &amp;y);&lt;br /&gt;    x ^= y;&lt;br /&gt;    y ^= x;&lt;br /&gt;    x ^= y;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Float Swap Function&lt;br /&gt;_f void swap(float&amp; x, float&amp; y) {&lt;br /&gt;    swap((int&amp;)x, (int&amp;)y);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Technically this isn't very useful when sticking with high-level c++, especially since floating point operations are generally compiled to use the x87 fpu (so the floats will be moved back into gprs, and end up being slower than a regular swap); also this will confuse the compiler more so that's another reason it won't generate as good code; but if you're dealing with SSE directly, the xor trick can be useful.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5674797630756947309?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5674797630756947309/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/xor-swap-trick-and-addsub-swap-trick.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5674797630756947309'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5674797630756947309'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/xor-swap-trick-and-addsub-swap-trick.html' title='xor swap trick and add/sub swap trick'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4359905846911041999</id><published>2010-07-08T19:59:00.004-04:00</published><updated>2010-07-08T20:23:46.464-04:00</updated><title type='text'>So...</title><content type='html'>I had an idea.&lt;br /&gt;&lt;br /&gt;I was thinking of stuff I should post in this blog and then I came up with the idea of posting random code snippets/tricks that you can do (mostly will be c++/asm stuff).&lt;br /&gt;&lt;br /&gt;Hopefully you guys like that idea; its at least its something kind-of fun :D&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4359905846911041999?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4359905846911041999/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/so.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4359905846911041999'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4359905846911041999'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/07/so.html' title='So...'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-2700764626780214868</id><published>2010-06-29T20:21:00.003-04:00</published><updated>2010-06-29T20:26:46.540-04:00</updated><title type='text'>WTF</title><content type='html'>Woah its been over a year since my last blog update!?&lt;br /&gt;I could have sworn it was only 6 months tops, damn the notion of time slips away when you're a hermit :o&lt;br /&gt;&lt;br /&gt;Anyways, I'll probably try and revive this blog somewhat so its not dead :(&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-2700764626780214868?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/2700764626780214868/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2010/06/wtf.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2700764626780214868'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/2700764626780214868'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2010/06/wtf.html' title='WTF'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5700002239593656539</id><published>2009-06-09T03:53:00.002-04:00</published><updated>2009-06-09T03:56:19.080-04:00</updated><title type='text'>Man this was good</title><content type='html'>&lt;object width="425" height="344"&gt;&lt;param name="movie" value="http://www.youtube.com/v/q5st0b3ln5U&amp;amp;hl=en&amp;amp;fs=1&amp;amp;"&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;param name="allowscriptaccess" value="always"&gt;&lt;embed src="http://www.youtube.com/v/q5st0b3ln5U&amp;amp;hl=en&amp;amp;fs=1&amp;amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br /&gt;&lt;br /&gt;That's not one of my favorite FFVII songs, but the 'power' of that performance just made it sound awesome.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5700002239593656539?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5700002239593656539/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/06/man-this-was-good.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5700002239593656539'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5700002239593656539'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/06/man-this-was-good.html' title='Man this was good'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5118836189245882408</id><published>2009-05-02T04:28:00.003-04:00</published><updated>2009-05-02T04:39:33.164-04:00</updated><title type='text'>I finally passed Discrete Mathematics!</title><content type='html'>On the final exam that I needed at least a 42 on, I got a 56.&lt;br /&gt;After taking the class 4 times, I'm finally done with it and can forget everything I learned xD&lt;br /&gt;&lt;br /&gt;The best part is I can finally take my advanced programming classes (which I couldn't take before because Discrete Math was a prerequisite).&lt;br /&gt;&lt;br /&gt;The bad news is, the programming class I wanted to take for next semester was already full when I went to register, so I'll have to wait another semester to take it...&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Technically I 'Passed' Discrete Math the second time I took it with a D+, but my university has some policy that I need to get a C or better for it to count...&lt;br /&gt;Anyways, I finally got a C+, so I'm good to go..&lt;br /&gt;(Its also funny how this class totally fucked up my high GPA to an 'average' GPA, and made me lose all my scholarships)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5118836189245882408?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5118836189245882408/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/05/i-finally-passed-discrete-mathematics.html#comment-form' title='14 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5118836189245882408'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5118836189245882408'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/05/i-finally-passed-discrete-mathematics.html' title='I finally passed Discrete Mathematics!'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>14</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4274026731057073912</id><published>2009-05-01T04:06:00.004-04:00</published><updated>2009-05-01T04:12:57.301-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='greatness'/><category scheme='http://www.blogger.com/atom/ns#' term='brilliance'/><category scheme='http://www.blogger.com/atom/ns#' term='genius'/><title type='text'>Greatest Man that Ever Lived</title><content type='html'>Leonardo Da Vinci was a brilliant man.&lt;br /&gt;Probably the greatest man that ever lived.&lt;br /&gt;&lt;br /&gt;Wikipedia describes him as "an Italian polymath, being a scientist, mathematician, engineer, inventor, anatomist, painter, sculptor, architect, botanist, musician and writer."&lt;br /&gt;&lt;br /&gt;Considering he excelled in all those fields, that's extremely impressive.&lt;br /&gt;He's "god-like" if you will.&lt;br /&gt;&lt;br /&gt;I have to say I'm envious.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4274026731057073912?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4274026731057073912/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/05/greatest-man-that-ever-lived.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4274026731057073912'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4274026731057073912'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/05/greatest-man-that-ever-lived.html' title='Greatest Man that Ever Lived'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4249109346886305980</id><published>2009-04-24T22:01:00.003-04:00</published><updated>2009-04-24T22:12:59.139-04:00</updated><title type='text'>42</title><content type='html'>The grade I needed to get on my final exam to pass my Discrete Math class, just so happened to be the answer to the universe... 42.&lt;br /&gt;&lt;br /&gt;If I got 42 or higher, then I can pass the class with a 70% C.&lt;br /&gt;(I need a C or higher for it to count as passing)&lt;br /&gt;&lt;br /&gt;I've been sick with the flu all week, so I didn't have a chance to study. I really fucking hope I got 42% or higher, I'll probably drop out of my University if I didn't... (I can't stand taking this class a 5th time!)&lt;br /&gt;&lt;br /&gt;If I do drop out of Uni, I'll probably join one of those video-game colleges, and get a degree in "game and simulation programming."&lt;br /&gt;The degree doesn't look as good as a "Computer Science" degree, but its better than nothing. And its probably a lot funner to achieve.&lt;br /&gt;Also, my grades would be a lot higher if most my classes were about programing games (I think I've mentioned in a previous post, that I'm only good at stuff I enjoy).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4249109346886305980?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4249109346886305980/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/42.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4249109346886305980'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4249109346886305980'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/42.html' title='42'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-1356958970141868364</id><published>2009-04-10T06:08:00.003-04:00</published><updated>2009-04-10T06:22:14.573-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='video'/><category scheme='http://www.blogger.com/atom/ns#' term='megaman'/><category scheme='http://www.blogger.com/atom/ns#' term='protoman'/><category scheme='http://www.blogger.com/atom/ns#' term='awesome'/><category scheme='http://www.blogger.com/atom/ns#' term='videogames'/><category scheme='http://www.blogger.com/atom/ns#' term='NES'/><title type='text'>Awesome Megaman Rap Video</title><content type='html'>One of my favorite video game series is the Megaman series.&lt;br /&gt;A friend at work recommended me to watch this cool video on youtube:&lt;br /&gt;&lt;br /&gt;&lt;object width="425" height="344"&gt;&lt;param name="movie" value="http://www.youtube.com/v/xDeGpZ3z7js&amp;amp;hl=en&amp;amp;fs=1"&gt;&lt;/param&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;/param&gt;&lt;param name="allowscriptaccess" value="always"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/xDeGpZ3z7js&amp;amp;hl=en&amp;amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br /&gt;&lt;br /&gt;I'm not too into rap music, but this song was pretty good.&lt;br /&gt;Its got some awesome lines:&lt;br /&gt;Heatman: "I got a face for radio and a box for a suit"&lt;br /&gt;Megaman "Capcom really didn't spend much time on you..."&lt;br /&gt;&lt;br /&gt;Windman and Airman's raps are my favorites, but they're all cool.&lt;br /&gt;Any megaman fan should watch the video xD&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-1356958970141868364?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/1356958970141868364/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/awesome-megaman-rap-video.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1356958970141868364'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/1356958970141868364'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/awesome-megaman-rap-video.html' title='Awesome Megaman Rap Video'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-3592025514715778426</id><published>2009-04-08T18:45:00.004-04:00</published><updated>2009-04-08T19:15:24.896-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='sleep'/><category scheme='http://www.blogger.com/atom/ns#' term='life'/><category scheme='http://www.blogger.com/atom/ns#' term='day'/><title type='text'>Sleep is a double-edged sword.</title><content type='html'>Sleep is pretty awesome, it helps rest your mind and helps improve memory and all that good stuff.&lt;br /&gt;&lt;br /&gt;But sadly sleep has its negatives, the main one being it takes away a lot of free time.&lt;br /&gt;Or it can make you not want to wake-up, and you'll be late for work or school (happens to me every day xD)&lt;br /&gt;Another problem is if you want to do something, but can't because you're too tired and need to sleep. Or if you just can't think straight because of lack of sleep.&lt;br /&gt;&lt;br /&gt;So I've often pondered if life would be better without sleep.&lt;br /&gt;The main problem that arises with this is that, if people didn't sleep, then work and school would most-likely be a lot longer. And that doesn't sound like a good thing xD&lt;br /&gt;&lt;br /&gt;A compromise would be if the world rotated slower, and a day would be something like 27 hours instead of 24 hours.&lt;br /&gt;This would allow for 3 more hours of sleep a day, and most people with busy lives would probably benefit from this.&lt;br /&gt;&lt;br /&gt;Of course that also has negatives as well. For instance, if you're waiting for a certain day to happen, you'll have to wait longer. In fancy math terms the extra time you'd have to wait is (3 * n) hours longer where n is the number of days.&lt;br /&gt;&lt;br /&gt;Furthermore, if you're having a bad day, and want the day to end, you'll have to endure that bad day for another 3 hours =D.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;So really, I'm not sure what could be done to solve the problems of sleep. All options seem to have their ups and downs.... but that seems to be the case with most things in 'life'.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-3592025514715778426?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/3592025514715778426/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/sleep-is-double-edged-sword.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3592025514715778426'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/3592025514715778426'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/04/sleep-is-double-edged-sword.html' title='Sleep is a double-edged sword.'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-5698738821331751754</id><published>2009-03-28T01:17:00.006-04:00</published><updated>2009-03-28T01:43:07.995-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Earth Day'/><category scheme='http://www.blogger.com/atom/ns#' term='waste'/><category scheme='http://www.blogger.com/atom/ns#' term='earth'/><category scheme='http://www.blogger.com/atom/ns#' term='energy'/><title type='text'>Earth Day?</title><content type='html'>http://www.google.com/intl/en/earthhour/2009/&lt;br /&gt;&lt;br /&gt;Heh this is pretty funny, they want us to turn off our lights for an hour? What for?&lt;br /&gt;&lt;br /&gt;I'm all for cleaner sources of energy and a cleaner planet earth, however we need new technology that's more efficient, we shouldn't have to use technology less just because its inefficient.&lt;br /&gt;&lt;br /&gt;Probably ~40% of the energy in the things we use daily is wasted due to inefficient technology (just my guess).&lt;br /&gt;&lt;br /&gt;PSU's iirc are at-most like 80% efficient, and standard lightbulbs waste like 50% of their energy as heat (i've totally forgotten the exact statistics of these things, so they might be off).&lt;br /&gt;&lt;br /&gt;But the point is, we don't need to use technology less to conserve energy, we need to make technology better!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-5698738821331751754?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/5698738821331751754/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/earth-day.html#comment-form' title='11 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5698738821331751754'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/5698738821331751754'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/earth-day.html' title='Earth Day?'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>11</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4477401721502902029</id><published>2009-03-25T00:56:00.003-04:00</published><updated>2009-03-25T01:25:32.810-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='graph theory'/><category scheme='http://www.blogger.com/atom/ns#' term='theory'/><category scheme='http://www.blogger.com/atom/ns#' term='discrete math'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='math'/><title type='text'>Discrete Mathematics Sucks</title><content type='html'>I've taken Discrete Mathematics 3 times, and I'm on my 4th try &gt;&lt;&lt;br /&gt;I feel pretty retarded taking the same class 4 times, and it especially hurts when I see people that are dumber than me passing the class :/&lt;br /&gt;&lt;br /&gt;I'm one of those people that are only good at stuff they enjoy. If I don't enjoy doing something, or if I see no real-benefit from it, I won't apply myself and just half-ass it (or in the case of discrete math, just procrastinate and not study till the-day-of the test :o)&lt;br /&gt;&lt;br /&gt;The class is basically a bunch of different advanced math courses/theories combined into 1 class. It needed for all Computer Science majors at my school, so it *should* have something to do with computers, but it really doesn't :/&lt;br /&gt;&lt;br /&gt;Seriously, I spend most my days programming shit, and I really don't see much practical use for discrete mathematics. There may be some cases where you can use graph theory to help with stuff like shortest path algorithms, but there's a big difference between programming 'graph theory', and math graph theory.&lt;br /&gt;&lt;br /&gt;Basically 'graph theory' or any other aspect of discrete mathematics to a mathematician is all about &lt;span style="font-weight: bold;"&gt;proving&lt;/span&gt; or &lt;span style="font-weight: bold;"&gt;showing&lt;/span&gt; something is true for all possible cases, regardless of the practicallity of actually implementing the algorithm. To a programmer its just "does this work good enough for what I need, and is it fast?"... See the difference? :p&lt;br /&gt;&lt;br /&gt;Now, what good is an algorithm if its not practical to actually use? Or if you'll never use it? I love programming because I can create and view my creation. With mathematics you theorize and.... wait I guess that's it!? oO&lt;br /&gt;&lt;br /&gt;Its funny, because back in high school I took Honors and Advanced Placement math courses, and got very good grades. I used to think math was pretty fun and easy... but then when I got to college I realized that the math in high school was "bullshit fake math."&lt;br /&gt;&lt;br /&gt;College math was a punch in the face, I actually &lt;span style="font-weight: bold;"&gt;had to&lt;/span&gt; study!? wtf! The bullshit fake high school math courses only 'taught' me that I didn't have to study for math courses because they were easy... I got pretty pissed when I learned what 'real math' was after taking some university math classes :/&lt;br /&gt;&lt;br /&gt;Anyways, the point of this blog-post is:&lt;br /&gt;1) Discrete Mathematics is pretty useless, and shouldn't be mandatory for Computer Science Majors.&lt;br /&gt;2) High School mathematics 'prepares' you badly for college-level math, by giving you false expectations that it will be easy.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4477401721502902029?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4477401721502902029/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/discrete-mathematics-sucks.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4477401721502902029'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4477401721502902029'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/discrete-mathematics-sucks.html' title='Discrete Mathematics Sucks'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-319559633085412374</id><published>2009-03-23T02:17:00.006-04:00</published><updated>2009-03-23T02:53:15.524-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='word verification'/><category scheme='http://www.blogger.com/atom/ns#' term='comments'/><category scheme='http://www.blogger.com/atom/ns#' term='options'/><category scheme='http://www.blogger.com/atom/ns#' term='customizations'/><title type='text'>Hmm</title><content type='html'>I realized that the default option for comments is that you need an account to leave them. So I just changed it so that anyone can leave a comment, and I also disabled the word verification since those things are so annoying!&lt;br /&gt;&lt;br /&gt;The worst part about word verification is that the text they make you type in is usually sooo warped that it takes a couple tries to type in the correct word &gt;&lt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-319559633085412374?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/319559633085412374/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/hmm.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/319559633085412374'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/319559633085412374'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/hmm.html' title='Hmm'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6684098291897902270</id><published>2009-03-23T01:32:00.002-04:00</published><updated>2009-03-23T02:28:33.669-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='misconceptions'/><category scheme='http://www.blogger.com/atom/ns#' term='theory'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='math'/><title type='text'>Programming != Math</title><content type='html'>There's a big misconception a lot of people have where they think in order to be a programmer, you have to be excellent at math or be a mathematician. This is absolutely false for most types of programming, or at least very misleading.&lt;br /&gt;&lt;br /&gt;Rather than saying you have to be good at math, its more correct to say you have to be good at thinking logically or procedurally. When you program you have to think about the goal you want to accomplish within the program you're writing, and then think of the step-by-step way to achieve that goal using the 'instructions' made accessible to you by the programming language.&lt;br /&gt;&lt;br /&gt;But notice that 'thinking logically' and 'mathematics' aren't the same thing. Of course being good at math is definitely a benefit to programming; if you know certain mathematical rules you might be able to simplify or optimize parts of your program, but its not a necessity for most types of programming.&lt;br /&gt;&lt;br /&gt;Now there are some fields of programming where math is more crucially used, a 3d game programmer for instance is going to use more math than a programmer developing a word processor. But if you take all the types of programmers in the world, most programmers rarely have need for any advanced-math in their applications.&lt;br /&gt;&lt;br /&gt;Personally I believe programming is more practical than mathematics anyways. Programmers create things that are useful to people, whereas mathematicians come up with theories that 95% of the time don't have any practical value.&lt;br /&gt;&lt;br /&gt;I always wonder why people want to be mathematicians, what the hell are they going to do with that mathematical knowledge? I guess that's why most of them just go on to be professors or teachers, since they can't find a real job that practically applies that knowledge :p&lt;br /&gt;&lt;br /&gt;So bottom line is:&lt;br /&gt;1) You don't have to be a mathematician to be a programmer.&lt;br /&gt;2) Knowledge is useless if its not put to a practical use.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6684098291897902270?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6684098291897902270/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/programming-math.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6684098291897902270'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6684098291897902270'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/programming-math.html' title='Programming != Math'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-6084504849254914143</id><published>2009-03-21T23:01:00.000-04:00</published><updated>2009-03-22T00:13:19.333-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ps2'/><category scheme='http://www.blogger.com/atom/ns#' term='VU'/><category scheme='http://www.blogger.com/atom/ns#' term='playstation 2'/><category scheme='http://www.blogger.com/atom/ns#' term='emulation'/><category scheme='http://www.blogger.com/atom/ns#' term='pcsx2'/><category scheme='http://www.blogger.com/atom/ns#' term='microVU'/><title type='text'>What is microVU?</title><content type='html'>Well earlier today on the &lt;a href="http://forums.pcsx2.net/"&gt;pcsx2 forums&lt;/a&gt; someone asked this question, and I guess I could go further into detail here as well as give a nice overview on PCSX2 and the Sony Playstation 2 (it should be an interesting way to kick-start this blog).&lt;br /&gt;&lt;br /&gt;Well as I mentioned in my first post, the main project I work on is a PS2 emulator called "PCSX2".&lt;br /&gt;For those of you unfamiliar with emulation, it's basically the idea to mimic or 'emulate' one system on another system.&lt;br /&gt;In the case of PCSX2, we are emulating the Playstation 2 system on a PC. So basically it lets you play ps2 games on your PC! :)&lt;br /&gt;&lt;br /&gt;The ps2 is a powerful beast, and I don't think much people understand how difficult properly emulating the system is. Its not uncommon for people to belittle the project or to flame it with hateful remarks (but I guess I can talk about that in another post :p)&lt;br /&gt;&lt;br /&gt;Basically to make an emulator, you need to have a solid understanding of how the system you're emulating works at a low level. In the case of the ps2, it has multiple different processors and units that need to be emulated correctly, and it also has to be programed in a way so that the components can sync and 'talk' to each other nicely.&lt;br /&gt;&lt;br /&gt;The PS2's main component is the Emotion Engine (EE), this is the 'heart' of the system which also includes 2 co-processors: COP1 (FPU), and COP2 (VU0 in macro-mode).&lt;br /&gt;In terms of PCSX2, we currently use dynamic recompilers to emulate the EE.&lt;br /&gt;A 'dynamic recompiler' is an emulation approach in contrast to an 'interpreter' (which is generally alot slower and easier to code).&lt;br /&gt;&lt;br /&gt;The idea of a recompiler is to take the ps2's native language or 'instructions' and to translate it into something your PC understands. After it translates alot of instructions, it saves them in memory in 'blocks'. A block is basically a bunch of instructions that have been translated.&lt;br /&gt;Later on when a game wants to 'read' an instruction, the recompiler would look-up a compatible block, and start 'executing' that block of code.&lt;br /&gt;&lt;br /&gt;This approach is alot faster than an interpreter because it only has to translate the code once, and then can read the saved translated code as much times as needed.&lt;br /&gt;An interpreter however doesn't 'save' any translated code, but instead just calls a function whenever an opcode needs to be executed (the overhead for the function calling, as well as the lack of optimizations that can be made, are some of the reasons interpreters are so slow).&lt;br /&gt;&lt;br /&gt;Well to get back to what I was saying, PCSX2 currently uses recompilers for its EE emulation (it also has interpreters for the EE, but they're really slow). Our current implementation of the EE recompiler is really a mess quite-frankly. Most of the pcsx2 team agrees we need a complete rewrite of the recompilers eventually, and hopefully next-time around it'll be cleaner and faster :)&lt;br /&gt;&lt;br /&gt;To get back to describing the PS2, in addition to the EE, it also has 2 Vertex Unit Processors (VU0 and VU1), a Graphic Synthesizer (GS), various DMA units (vif, sif, gif, ...),  2 Sound Processing Units (SPUs), an Input/Output unit (IOP),  a MPEG-decoding unit (IPU), and various other components I didn't mention.&lt;br /&gt;Emulating all these units is alot of work, and syncing them so they work 'together' is ridiculously complex (many of pcsx2's problems is incorrectly syncing these units).&lt;br /&gt;&lt;br /&gt;Well now I guess I can finally get to the original question: "What is microVU?"&lt;br /&gt;microVU is what I named the new VU recompilers I'm working on.&lt;br /&gt;Currently PCSX2 uses the VU recompilers named "Super VU" a.k.a. "zerorecs", but they're incorrect when it comes to properly following the VU's pipeline rules, also they're coded in a way that makes them un-threadable.&lt;br /&gt;The goal for microVU is to properly emulate the VU's pipeline and possibly be even faster than Super VU. Additionally, microVU is coded with threading in mind, and eventually it should be threadable which would enable big speed-gains for quad-core CPU users, and possibly nice speed-gains for dual-core users as well.&lt;br /&gt;&lt;br /&gt;Since this post is already a Wall of Text, I guess I'll stop here for now, and possibly go over some more stuff in future posts :p&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-6084504849254914143?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/6084504849254914143/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/what-is-microvu.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6084504849254914143'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/6084504849254914143'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/what-is-microvu.html' title='What is microVU?'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-2543858175797658864.post-4272358384998163504</id><published>2009-03-21T18:32:00.000-04:00</published><updated>2009-03-21T18:57:56.747-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='something'/><category scheme='http://www.blogger.com/atom/ns#' term='cotton'/><category scheme='http://www.blogger.com/atom/ns#' term='starting blog'/><category scheme='http://www.blogger.com/atom/ns#' term='beginning'/><category scheme='http://www.blogger.com/atom/ns#' term='cottonvibes'/><title type='text'>Starting this blog.</title><content type='html'>&lt;span style="font-weight: bold;"&gt;&lt;span style="font-style: italic;"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;Well this is my new blog.&lt;br /&gt;&lt;br /&gt;Here I'll post random things dealing with the projects I work on, as well as any other stuff I feel like talking about =D&lt;br /&gt;&lt;br /&gt;I guess I should post a bit of background info about myself for those that don't know me.&lt;br /&gt;&lt;br /&gt;Well I go by the nick 'cottonvibes', I'm a 20 year old university student living somewhere in the USA  (exact location is hidden to prevent my privacy ;p)&lt;br /&gt;&lt;br /&gt;Mostly I spend my time coding for a well-known project called &lt;a href="http://www.pcsx2.net/"&gt;PCSX2&lt;/a&gt; (the world's most advanced ps2 emulator! :p). I've been working on PCSX2 for about a year, but 'officially' I've only been coding for the project about a few months.&lt;br /&gt;&lt;br /&gt;Before that I was one of the founders of &lt;a href="http://code.google.com/p/pcsx2-playground/"&gt;PCSX2 Playground&lt;/a&gt;, which was a PCSX2 branch project that quickly gained popularity, and eventually got merged into the official PCSX2 project (and thats how the rest of the playground team and I got on the official PCSX2 team).&lt;br /&gt;&lt;br /&gt;Aside from PCSX2, I've worked on various other random private coding projects, mostly just for fun by myself.&lt;br /&gt;&lt;br /&gt;I'm halfway done with my own NES emulator called "cottonNES", but due to PCSX2 taking up most my time, I've had to put that project on hold.&lt;br /&gt;&lt;br /&gt;...well this probably is enough writing for my first blog post, so I guess I'll just stop here and write some more random gibberish later :D&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/2543858175797658864-4272358384998163504?l=cottonvibes.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://cottonvibes.blogspot.com/feeds/4272358384998163504/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/starting-this-blog.html#comment-form' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4272358384998163504'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/2543858175797658864/posts/default/4272358384998163504'/><link rel='alternate' type='text/html' href='http://cottonvibes.blogspot.com/2009/03/starting-this-blog.html' title='Starting this blog.'/><author><name>cottonvibes</name><uri>http://www.blogger.com/profile/15542648017139504620</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://2.bp.blogspot.com/_WwIahqE-1Co/Scc070ll1rI/AAAAAAAAAAM/dLU8mhhWs0w/S220/myFace.bmp'/></author><thr:total>10</thr:total></entry></feed>
