<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Learn C++ &#187; General Programming</title>
	<atom:link href="http://www.learncpp.com/category/general-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.learncpp.com</link>
	<description></description>
	<lastBuildDate>Mon, 19 Jul 2010 06:46:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A PHP script to unzip files with file overwriting</title>
		<link>http://www.learncpp.com/general-programming/a-php-script-to-unzip-files-with-file-overwriting/</link>
		<comments>http://www.learncpp.com/general-programming/a-php-script-to-unzip-files-with-file-overwriting/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 20:53:09 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[General Programming]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/general-programming/a-php-script-to-unzip-files-with-file-overwriting/</guid>
		<description><![CDATA[Many web hosts use CPanel, as it offers a fairly intuitive way for people to manage their accounts.  CPanel comes with a file manager that is functional, but somewhat clunky.  Although CPanel offers a mechanism for extracting archives (.zip and .gz), this mechanism has one major downside: when extracting .zip files, currently existing [...]]]></description>
			<content:encoded><![CDATA[<p>Many web hosts use CPanel, as it offers a fairly intuitive way for people to manage their accounts.  CPanel comes with a file manager that is functional, but somewhat clunky.  Although CPanel offers a mechanism for extracting archives (.zip and .gz), this mechanism has one major downside: when extracting .zip files, currently existing files will not be overwritten.  This makes upgrading software that is distributed in .zip packages very difficult.</p>
<p>To work around this limitation, I wrote a PHP script that allows users to extract .zip files and overwrite current files.  It presents the user with a list of all the .zip files in the directory, and allows him/her to submit one for extraction.  The whole process is quite intuitive.  Here is what the interface looks like:</p>
<blockquote><p>
Please choose a file to unzip: <br /><FORM action="" method=""><br />
<input type="radio" name="file" value=test.zip> test.zip<br />
<input type="radio" name="file" value=test2.zip> test2.zip</p>
<p>Warning: Existing files will be overwritten.</p>
<input type="button" value="Unzip!"></FORM>
</p></blockquote>
<p>The selected file is then unzipped.</p>
<p>To use the script, simply follow this procedure:<br />
1) Upload this script via FTP (or paste the script into a new file) in the directory that contains the .zip file to unzip.<br />
2) Run your web browser, and point it at the script<br />
3) Select the file to unzip, and hit the &#8220;Unzip&#8221; button.</p>
<p>That&#8217;s it!</p>
<p><strong>Make sure you delete the script after running it, as leaving it on the machine could result in a security issue.</strong></p>
<p>unzip.php:</p>
<pre class="brush: php;">
&lt;?php
    // The unzip script
    // Created by Alex at http://www.learncpp.com
    //
    // This script lists all of the .zip files in a directory
    // and allows you to select one to unzip.  Unlike CPanel's file
    // manager, it _will_ overwrite existing files.
    //
    // To use this script, FTP or paste this script into a file in the directory
    // with the .zip you want to unzip.  Then point your web browser at this
    // script and choose which file to unzip.

    // See if there's a file parameter in the URL string
    $file = $_GET['file'];

    if (isset($file))
    {
       echo &quot;Unzipping &quot; . $file . &quot;&lt;br&gt;&quot;;
       system('unzip -o ' . $file);
       exit;
    }

    // create a handler to read the directory contents
    $handler = opendir(&quot;.&quot;);

    echo &quot;Please choose a file to unzip: &quot; . &quot;&lt;br&gt;&quot;;

    // A blank action field posts the form to itself
    echo '&lt;FORM action=&quot;&quot; method=&quot;get&quot;&gt;';

    $found = FALSE; // Used to see if there were any valid files

    // keep going until all files in directory have been read
    while ($file = readdir($handler))
    {
        if (preg_match (&quot;/.zip$/i&quot;, $file))
        {
            echo '&lt;input type=&quot;radio&quot; name=&quot;file&quot; value=' . $file . '&gt; ' . $file . '&lt;br&gt;';
            $found = true;
        }
    }

    closedir($handler);

    if ($found == FALSE)
        echo &quot;No files ending in .zip found&lt;br&gt;&quot;;
    else
        echo '&lt;br&gt;Warning: Existing files will be overwritten.&lt;br&gt;&lt;br&gt;&lt;INPUT type=&quot;submit&quot; value=&quot;Unzip!&quot;&gt;';

    echo &quot;&lt;/FORM&gt;&quot;;
?&gt;
</pre>
<p><p><hr>
Did you know that you can get a <a
 href="http://www.guidetoonlineschools.com/cpp_programming.html" rel="nofollow">C++
 programming degree</a> online?  There are many <a
 href="http://www.guidetoonlineschools.com/campus_schools.htm" rel="nofollow">online
 schools</a> that offer computer programming <a
 href="http://www.eecs.berkeley.edu/education/degrees.shtml">classes</a> and
 courses.  It's easy to get your <a
 href="http://www.guidetoonlineschools.com/ba_general_studies.html" rel="nofollow">online
 degree</a>, so start studying up on <a
 href="http://www.srh.noaa.gov/jetstream/">something</a> you love!
<br><hr></p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/general-programming/a-php-script-to-unzip-files-with-file-overwriting/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>5.7 &#8212; For statements</title>
		<link>http://www.learncpp.com/cpp-tutorial/57-for-statements/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/57-for-statements/#comments</comments>
		<pubDate>Tue, 26 Jun 2007 02:48:46 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>
		<category><![CDATA[C++ Tutorial]]></category>
		<category><![CDATA[General Programming]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/57-for-statements/</guid>
		<description><![CDATA[By far, the most utilized looping statement in C++ is the for statement.  The for statement is ideal when we know exactly how many times we need to iterate, because it lets us easily declare, initialize, and change the value of loop variables after each iteration.
The for statement looks pretty simple:

for (init-statement; expr1; expr2)
 [...]]]></description>
			<content:encoded><![CDATA[<p>By far, the most utilized looping statement in C++ is the <em>for statement</em>.  The for statement is ideal when we know exactly how many times we need to iterate, because it lets us easily declare, initialize, and change the value of loop variables after each iteration.</p>
<p>The for statement looks pretty simple:</p>
<pre>
for (init-statement; expr1; expr2)
   statement;
</pre>
<p>The easiest way to think about for loops is convert them into equivalent while loops.  In older versions of C++, the above for loop was exactly equivalent to:</p>
<pre>
// older compilers
init-statement;
while (expr1)
{
    statement;
    expr2;
}
</pre>
<p>However, in newer compilers, variables declared during the init-statement are now considered to be scoped inside the while block rather than outside of it.  This is known as loop scope.  Variables with <strong>loop scope</strong> exist only within the loop, and are not accessible outside of it.  Thus, in newer compilers, the above for loop is effectively equivalent to the following while statement:</p>
<pre>
// newer compilers
{
    init-statement;
    while (expr1)
    {
        statement;
        expr2;
    }
} // variables declared in init-statement go out of scope here
</pre>
<p>A <em>for statement</em> is evaluated in 3 parts:</p>
<p>1) Init-statement is evaluated.  Typically, the init-statement consists of variable declarations and assignments.  This statement is only evaluated once, when the loop is first executed.</p>
<p>2) The expression expr1 is evaluated.  If expr1 is false, the loop terminates immediately.  If expr1 is true, the statement is executed.</p>
<p>3) After the statement is executed, the expression expr2 is evaluated.  Typically, this expression consists of incremented/decrementing the variables declared in init-statement.  After expr2 has been evaluated, the loop returns to step 2.</p>
<p>Let&#8217;s take a look at an example of a for loop:</p>
<pre class="brush: cpp;">
for (int iii=0; iii &lt; 10; iii++)
    cout &lt;&lt; iii &lt;&lt; &quot; &quot;;
</pre>
<p>What does this do?  Although this looks somewhat confusing, let&#8217;s take it piece by piece.</p>
<p>First, we declare a loop variable named iii, and assign it the value 0.</p>
<p>Second, the iii < 10 is evaluated, and since iii is 0, 0 < 10 evaluates to true.  Consequently, the statement executes, which prints 0.</p>
<p>Third, After the statement executes, iii++ is evaluated, which increments iii to 1.  Then the loop goes back to the second step.</p>
<p>1 < 10 is evaluates to true, so the loop iterates again.  The statement prints 1, and iii is incremented to 2.  2 < 10 evaluates to true, the statement prints 2, and iii is incremented to 3.  And so on.</p>
<p>Eventually iii is incremented to 10, 10 < 10 evaluates to false, and the loop exits.</p>
<p>Consequently, this program prints the result:</p>
<pre>
0 1 2 3 4 5 6 7 8 9
</pre>
<p>For loops can be hard for new programmers to read -- however, experienced programmers love them because they are a very compact way to do loops of this nature.  Let's uncompact the above for loop by converting it into it's while-statement equivalent:</p>
<pre class="brush: cpp;">
{
    int iii = 0;
    while (iii &lt; 10)
    {
        cout &lt;&lt; iii &lt;&lt; &quot; &quot;;
        iii++;
    }
}
</pre>
<p>That doesn't look so bad, does it?  Note that the outer braces are necessary here, because iii goes out of scope when the loop ends (in newer compilers).</p>
<p>Here is an example of a for loop affecting a variable declared outside the for loop:</p>
<pre class="brush: cpp;">
// returns the value nBase ^ nExp
int Exponent(int nBase, int nExp)
{
    int nValue = 1;
    for (int iii=0; iii &lt; nExp; iii++)
        nValue *= nBase;

    return nValue;
}
</pre>
<p>This function returns the value nBase^nExp (nBase to the nExp power).</p>
<p>This is a straightforward incrementing for loop, with iii looping from 0 up to (but excluding) nExp.</p>
<p>If nExp is 0, the for loop will execute 0 times, and the function will return 1.<br />
If nExp is 1, the for loop will execute 1 time, and the function will return 1 * nBase.<br />
If nExp is 2, the for loop will execute 2 times, and the function will return 1 * nBase * nBase.</p>
<p>Although most for loops increment the loop variable by 1, we can decrement it as well:</p>
<pre class="brush: cpp;">
for (int iii = 9; iii &gt;= 0; iii--)
    cout &lt;&lt; iii &lt;&lt; &quot; &quot;;
</pre>
<p>This prints the result:</p>
<pre>
9 8 7 6 5 4 3 2 1 0
</pre>
<p>Alternately, we can change the value of our loop variable by more than 1 with each iteration:</p>
<pre class="brush: cpp;">
for (int iii = 9; iii &gt;= 0; iii -= 2)
    cout &lt;&lt; iii &lt;&lt; &quot; &quot;;
</pre>
<p>This prints the result:</p>
<pre>
9 7 5 3 1
</pre>
<p><strong>Off-by-one errors</strong></p>
<p>One of the biggest problems that new programmers have with for loops is off-by-one errors.  Off-by-one errors occur when the loop iterates one too many or one too few times.  This generally happens because the wrong relational operator is used in expr1 (eg. > instead of >=).  These errors can be hard to track down because the compiler will not complain about them -- the program will run fine, but it will produce the wrong result.</p>
<p>When writing for loops, remember that the loop will execute as long as expr1 is true.  Generally it is a good idea to test your loops using known values to make sure that they work as expected.  If your loop produces the right result when it iterates 0, 1, and 2 times, it will probably work for all number of iterations.</p>
<p><strong>Omitted expressions</strong></p>
<p>It is possible to write for loops that omit any or all of the expressions.  For example:</p>
<pre class="brush: cpp;">
int iii=0;
for ( ; iii &lt; 10; )
{
    cout &lt;&lt; iii &lt;&lt; &quot; &quot;;
    iii++;
}
</pre>
<p>This for loop produces the result:</p>
<pre>
0 1 2 3 4 5 6 7 8 9
</pre>
<p>Rather than having the for loop do the initialization and incrementing, we've done it manually.  We have done so purely for academic purposes in this example, but there are cases where not declaring a loop variable (because you already have one) or incrementing it (because you're incrementing it some other way) are desired.</p>
<p>Although you do not see it very often, it is worth noting that the following example produces an infinite loop:</p>
<pre>
for (;;)
    statement;
</pre>
<p>The above example is equivalent to:</p>
<pre>
while (true)
    statement;
</pre>
<p><strong>Null statements</strong></p>
<p>It is also possible to omit the statement part of a for loop.  This is called a <strong>null statement</strong>, and it is declared by using a single semicolon.</p>
<pre class="brush: cpp;">
for (int iii=0; iii &lt; 10; iii++)
    ;
</pre>
<p>This loop increments iii using the ++ operator 10 times.  When the statement is executed, the null statement evaluates to nothing, and consequently, doesn't do anything.  For readability purposes, the semicolon of a null statement is typically placed on it's own line.  This indicates that the use of a null statment was intentional, and makes it harder to overlook the use of the null statement.</p>
<p>Null statements can actually be used anywhere a regular statement can (though they typically aren't, since they serve no purpose other than as a do-nothing placeholder).  Because of this, it is easy to make the following mistake:</p>
<pre class="brush: cpp;">
if (nValue == 0);
    nValue = 1;
</pre>
<p>The programmer's intent was to assign nValue the value of 1 only if nValue had the value 0.  However, due to the misplaced semicolon after the if statement, this actually executes as:</p>
<pre class="brush: cpp;">
if (nValue == 0)
    ;
nValue = 1;
</pre>
<p>Consequently, nValue is set to 1 regardless of it's previous value!</p>
<p><strong>Multiple declarations</strong></p>
<p>Although for loops typically iterate over only one variable, sometimes for loops need to work with multiple variables.  When this happens, the programmer can make use of the comma operator in order to initialize or change the value of multiple variables:</p>
<pre class="brush: cpp;">
    for (int iii=0, jjj=9; iii &lt; 10; iii++, jjj--)
        cout &lt;&lt; iii &lt;&lt; &quot; &quot; &lt;&lt; jjj &lt;&lt; endl;
</pre>
<p>This loop initializes two variable: iii to 0, and jjj to 9.  It iterates iii over the range 0 to 9, and each iteration iii is incremented and jjj is decremented.</p>
<p>This program produces the result:</p>
<pre>
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
9 0
</pre>
<p>This is the only place in C++ where the comma operator typically gets used.</p>
<p><strong>Conclusion</strong></p>
<p>For loops are the most commonly used loop in the C++ language.  Even though it's syntax is typically a bit confusing to new programmers, you will see for loops so often that you will understand them in no time at all!</p>
<p><strong>Quiz</strong></p>
<p>1) Write a for loop that prints every other number from 0 to 20.</p>
<p>2) Write a function named SumTo() that takes an integer parameter named nValue, and returns the sum of all the numbers from 1 to nValue.</p>
<p>For example, SumTo(5) should return 15, which is 1 + 2 + 3 + 4 + 5.</p>
<p>Hint: Use a non-loop variable to accumulate the sum as you iterate from 1 to nValue, much like the Exponent() example above uses nValue to accumulate the return value each iteration.</p>
<p>3) What's wrong with the following for loop?</p>
<pre class="brush: cpp;">
// Print all numbers from 9 to 0
for (unsigned int nCount = 9; nCount &gt;= 0; nCount--)
    cout &lt;&lt; nCount &lt;&lt; &quot; &quot;;
</pre>
<p><strong>Quiz solutions</strong></p>
<p>1) <a class="solution_link_show" href="javascript:void(0)" onclick="wpSolutionToggle(document.getElementById('id243110231'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id243110231" style="display:none">
<pre class="brush: cpp;">
for (int iii=0; iii &lt;= 20; iii += 2)
    cout &lt;&lt; iii &lt;&lt; endl;
</pre>
</div>
<p>2) <a class="solution_link_show" href="javascript:void(0)" onclick="wpSolutionToggle(document.getElementById('id1158879924'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id1158879924" style="display:none">
<pre class="brush: cpp;">
int SumTo(int nSumTo)
{
    int nSum = 0;
    for (int iii=1; iii &lt;= nSumTo; iii++)
        nSum += iii;

    return nSum;
}
</pre>
</div>
<p>3) <a class="solution_link_show" href="javascript:void(0)" onclick="wpSolutionToggle(document.getElementById('id81027045'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id81027045" style="display:none">
This for loop executes as long as nCount >= 0.  In other words, it runs until nCount is negative.  However, because nCount is unsigned, nCount can never go negative.  Consequently, this for loop will run for-ever!  Generally, it's a good idea to avoid looping on unsigned variables unless necessary.
</div>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/58-break-and-continue/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 5.8 -- Break and continue</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter5" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/up.png" align=middle> Index</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/56-do-while-statements/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 5.6 -- Do while statements</a>
</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/57-for-statements/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Six language-independent ways to write better code</title>
		<link>http://www.learncpp.com/general-programming/six-language-independent-ways-to-write-better-code/</link>
		<comments>http://www.learncpp.com/general-programming/six-language-independent-ways-to-write-better-code/#comments</comments>
		<pubDate>Mon, 25 Jun 2007 17:35:56 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[General Programming]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/general-programming/six-language-independent-ways-to-write-better-code/</guid>
		<description><![CDATA[





One of the amazing things about working in a department with other coders is that you consistently see the same mistakes being made day after day, month after month, year after year.  Whether it&#8217;s due to general timidity, fear of criticism being taken personally, lack of a formal review process, or a company culture [...]]]></description>
			<content:encoded><![CDATA[<p><div style=display:block;float:right;margin: 5px 5px 5px 5px;>
<script type="text/javascript"><!--
google_ad_client = "pub-0588844875925051";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text_image";
//2007-06-15: 336x280
google_ad_channel = "4172701375";
//-->
</script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div><br />
One of the amazing things about working in a department with other coders is that you consistently see the same mistakes being made day after day, month after month, year after year.  Whether it&#8217;s due to general timidity, fear of criticism being taken personally, lack of a formal review process, or a company culture that does not encourage reflection and improvement, coders are often hesitant to give constructive criticism to other coders.  Without such criticism, coders often lack the opportunity to recognize and improve their coding skills, which leads to the same mistakes being repeated in the future.  And mistakes and bad habits by one coder on a team ultimately end up costing everyone time, which is always the most constrained resource in a production environment.  To minimize such bottlenecks, designing your code the right way the first time is paramount &#8212; and that means having good habits.</p>
<p>The following common sense suggestions have been gleaned from years of experience working both at the professional level and on large-scale personal projects.  This article is dedicated to my fellow programmers working at both the professional and hobbyist levels.</p>
<p><br clear="all"></p>
<hr />
<h3>1) Plan for extensibility</h3>
<p>This is perhaps the #1 issue that I run across on an almost daily basis.  Generally when we write a piece of code, we are doing so in response to trying to solve a very specific problem.  It is very easy to get stuck in the mindset of &#8220;here is the problem I have to solve, and here is how I am going to solve it&#8221;.  Then a specific solution tailored to that individual problem is implemented, which works great in the short run, but ultimately leads to huge maintenance issues down the road.</p>
<p>Extensibility should always be kept in mind for any piece of code you write.  Whether due to feature creep (features not originally anticipated), faster computers, or more sophisticated customers doing more complex things with your program, specific solutions implemented today are going to need to be extended to do something else tomorrow.  For example, you may write a small library to handle working with BMP files.  Tomorrow your customers are going to want JPEG support too.  Today you&#8217;re writing certain information to a file, tomorrow there will be 3 times that information that needs to be written to file, and the old files will still need to work too.  Your customers are using your software to do a task today, tomorrow they&#8217;ll want to do a task with 10 times as many fields, objects, or whatever unit is appropriate to your software.  If your code isn&#8217;t already set up to support extension, you&#8217;ll end up bogged down in maintenance, and every addition will cause your software to become more complex and unmaintainable.</p>
<p>There are many simple suggestions that can help extensibility: Don&#8217;t code specific solutions &#8212; code generic, reusable libraries.  Don&#8217;t assume the length or size of anything will be constant.  Version all your user-data files.  Use encapsulation.</p>
<p>By far the most time spent in any stage of the software life-cycle will be spent in the maintenance phase &#8212; so it is imperative to design your software in a way that encourages easy maintenance &#8212; and that means designing for extensibility.</p>
<hr />
<h3>2) Don&#8217;t use magic numbers</h3>
<p>Magic numbers are numbers that are hard-coded into your project, usually without explanation.  They often represent explicit assumptions that are being made about the size, length, or value of something.  Because magic numbers tend to be somewhat arbitrary, they often do not carry any meaning in and of themselves, which can ultimately make your code harder to read, understand, and maintain.</p>
<p>For example, you might see a piece of code that looks like this:</p>
<pre>
for iii = 0 to 15
    if (slot[iii].type == 12)
        return true;
</pre>
<p>What do the numbers 15 and 12 mean in this context?  Why were these specific numbers picked?  These numbers do not convey any specific information to the reader about what is going on in this segment of code.</p>
<p>Ideally, magic numbers should be parameterized &#8212; the mechanisms for doing this vary from language to language, but use of symbolic constants (via const variables, #defines, or enumerated values, for example) are much better choices.  The above code, rewritten using symbolic constants:</p>
<pre>
for iii = 0 to MAX_INVENTORY_SLOTS
    if (slot[iii].type == TYPE_ITEM_POTION)
       return true;
</pre>
<p>Suddenly, this code makes a lot more sense.  Without even knowing much about the rest of the program, it&#8217;s pretty obvious that we&#8217;re examining the inventory (probably of a creature), looking to see if there are any potions.</p>
<p>Furthermore, using symbolic constants instead of magic numbers aid extensibility.  In the future, your character may want 20 inventory slots instead of 15.  Using magic numbers, you&#8217;d have to search the code for all instances of the number 15, and change them by hand.  Changing a symbolic constant usually involves searching for MAX_INVENTORY_SLOTS and changing the definition from 15 to 20.  This can not only save a lot of time, but also prevent mistakes caused by inadvertently changing the wrong magic numbers.  For example, consider this snippet of code:</p>
<pre>
if (iii == 15)
    return;
</pre>
<p>What does this 15 mean?  Is it the maximum number of inventory slots (in which case you should change it), or does it mean something else (in which case you shouldn&#8217;t)?  Without understanding the context of the code around it, it&#8217;s impossible to tell.  That makes doing mass changes when you need to expand the number of inventory slots dangerous, as it introduces the error of inadvertently breaking other code that already works.</p>
<p>(Author&#8217;s note: using better variable names than iii is also recommended)</p>
<hr />
<h3>3) Document why, not what</h3>
<p>Almost all coders intuitively understand the maintenance value of good comments.  And yet, many programmers misuse comments in such a way that they add little to no value to the maintenance process.</p>
<p>Here is an example of a comment that does not add anything:</p>
<pre>
# Loop through all of the inventory slots
for i = 0 to MAX_INVENTORY_SLOTS
</pre>
<p>It&#8217;s pretty obvious what the code is doing even without the unnecessary comment.</p>
<p>Here&#8217;s another useless comment that you sometimes see:</p>
<pre>
iii = iii + 1; // increment iii
</pre>
<p>Comments should not be used to describe <em>what</em> the code is doing.  The syntax of the code tells what the code is doing.  A good comment tells <em>how</em> or <em>why</em> the code is doing what it&#8217;s doing.  <em>How</em> comments are often useful for outlining the algorithm that the code is using to solve a problem:</p>
<pre>
/* The following code scans the entire dungeon looking for spots
    where a hallway connects to a room.  This done by examining
    adjacent square of the dungeon.  If a square is a hallway
    square and the hallway square has one adjacent room
    neighbor, this is a candidate square. */

// Algorithm implemented here
</pre>
<p><em>How</em> comments are best utilized at the top of a function or block of code, as they allow a programmer to understand whether the following code is relevant to their interests at the time without having to read and comprehend all of the code in the block.  This can save a lot of time during the maintenance phase when trying to locate a particular segment of code.</p>
<p><em>Why</em> comments are ideal as individual line of code comments.  <em>Why</em> comments should explain why the coder is doing something specific:</p>
<pre>
// Because all creatures have been priority sorted by time,
//   if this creature (which is the next to move) has a time
//   greater than the current time, we can advance the
//   CurrentTime variable so that the creature can take it's
//    move.
if (pCreature->GetTime() > CurrentTime)
    CurrentTime = pCreature->GetTime()
</pre>
<p>If your code really needs a comment to explain <em>what</em> the code is doing, your code probably needs to be refactored or simplified, not commented.</p>
<hr />
<h3>4) Don&#8217;t reinvent the wheel</h3>
<p>Programmers in object-oriented languages are often tempted to write their own classes to do things which have already been solved a million times by other coders.  This is particularly true with container classes.  While writing your own array and linked list container classes can be a good academic exercise, or even fun if you enjoy that kind of thing, why do so when you can reuse one that&#8217;s already been written?  This not only saves you the time needed to implement the class, it saves you the time of having to test and debug it, and future versions of the class may provide additional functionality without you doing anything other than install them.  Furthermore, if the container class is part of the language (such as in C++&#8217;s standard template library), programmers reading your code will be more likely to already be familiar with how those containers work, reducing the time needed for new programmers to become familiar with the code.</p>
<p>Reinventing the wheel can also lead to code duplication, which makes your project more complex and more difficult to maintain.  If you have two or three pieces of code doing the same task, you may need to modify all of them to enhance their functionality.  This is effectively wasted time that could be used elsewhere.  Furthermore, it leads to confusion over which version has what responsibility and makes finding errors more difficult (because it&#8217;s harder to isolate which code is being used for a particular problem).</p>
<p>One of the complaints heard about some libraries such as the C++ standard template library is that the interface is awkward.  If that is the case for you, rather than rewrite a container that already exists, create a wrapper class and wrap the functionality you use most often in your own interface.  Generally, the performance penalty for doing so is small, you can tailor the interface to your needs, and if you need to extend the functionality of the underlying library, you already have a convenient place to do so.</p>
<p>There are many great resources already available on the web where free code can be found, from <a href="http://www.koders.com/">Koders.com</a>, <a href="http://www.google.com/codesearch">Google code search</a>, <a href="http://www.krugle.com/">Krugle</a>, <a href="http://sourceforge.net/">Sourceforge </a>, and <a href="http://www.codeproject.com/">Code Project</a>, amongst others.  Use them.</p>
<p>There are also plenty of good free libraries out there that may already solve the problems you&#8217;re trying to solve: as an example, <a href="http://www.libsdl.org/">SDL</a>, <a href="http://freetype.sourceforge.net/index2.html">FreeType</a>, and <a href="http://www.wxwidgets.org/">WxWidgets</a> are all examples of cross-platform libraries that may offer easy solutions to your problems.  Even though you must learn how to use them, often the time needed do so is significantly less than the time needed to implement your own solution, let alone debug and maintain it!</p>
<p>Note: Be careful of licensing issues, especially if using open source code in commercial projects!</p>
<hr />
<h3>5) Work incrementally</h3>
<p>One of the biggest mistakes hobbyist programmers make is to try and implement too much at a time without spending adequate time testing each section.  As a result, bugs start piling on top of other bugs, not only making them harder to find and isolate, but also making the number of bugs needing be squashed seem unmanageable.</p>
<p>A much better idea is to work incrementally.  After each section of code has been written, think, &#8220;How am I going to test this?&#8221;, and then actually test it.  If you find any bugs, either in the code you&#8217;ve just written, or in code that your code is relying on, those bugs should be taken care of immediately.</p>
<p>Focus down on one area at a time.  Work on one particular piece of code until it does what you want.  Every time you switch between areas, your brain has to do a context switch, which makes you less productive and wears you out faster.  If you&#8217;re writing a container class of some sort, don&#8217;t implement only the portion you need now and come back to do the rest later.  If you know you&#8217;re going to need it later, implement it now, while the details are still fresh in your mind.  It is truly amazing how quickly one forgets the details of what one has already coded!  You&#8217;ll be less likely to make mistakes, and your testing plan will be more coherent and structured.</p>
<hr />
<h3>6) Find someone willing to criticize your work</h3>
<p>As alluded to in the introduction of this article, finding someone willing to give you constructive feedback is one of the best ways to learn.  If they are willing, this person should be consulted even before you start coding!  Bring an outline of your proposed solution to them, explain it to them, and have them give you feedback on it.  In the process of explaining it to them, you will not only solidify the problem in your own mind, but they will also be able to offer you advice on things that you may not have foreseen, such as potential problem areas, better algorithms that you had not though of, or where you&#8217;re intending to reinvent the wheel.</p>
<p>Once you have coded your solution, have someone take a look at it.  They will more than likely be able to point out places where you haven&#8217;t made your code extensible enough, where you have used magic numbers, where you haven&#8217;t documented well.</p>
<p>Remember, on a team, everyone is in it together.  When your teammate writes bad code now, it could be you that ends up having to extend it tomorrow.  Consequently, it&#8217;s worth everyone&#8217;s time to work together to make sure good habits are utilized up front, so the penalties aren&#8217;t so severe down the road.  If you&#8217;re working alone, having good habits will help keep your code structured and flexible, making it easier to work with and less trying on your patience.</p>
<hr />
<h3>Conclusion</h3>
<p>Although much of the above seems obvious, these things are often shortcut in situations where there is time-pressure to get things done.  However, these suggestions should not be thought of as preventative measures, they should be thought of as investments.  Spend a little bit of extra time now, save a lot of extra time down the road.  &#8220;But what if I don&#8217;t have a lot of time now?&#8221;, you ask.  Do it anyway.  Right now is already down the road from some time in the past, and as code ages, the more these kinds of mistakes tend to compound.  Doing the right thing now will give you more time in the future to continue doing the right thing.  Ultimately, that not only makes for a higher quality product, it makes for a happier programmer.</p>
<p>If you believe this article was worthwhile, please recommend it using the social bookmarking icons below.  Many thanks, and happy coding.</p>
<p>Related articles:</p>
<ul>
<li><a href="http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/">Eight C++ programming mistakes the compiler won&#8217;t catch</a>
<li><a href="http://www.learncpp.com/computer-game-programming/three-questions-that-need-to-be-answered-before-you-start-writing-your-game/">Three questions that need to be answered before you start writing your game</a>
</ul>
<p><p><hr>
Learning to write <a
 href="http://www.barcodediscount.com/catalog/zebra/">better</a> code is
 tricky, but without a <a href="http://www.barcodediscount.com/">barcode
 scanner</a>, there will be some codes you'll never understand.  Barcode and
 <a href="http://www.barcodediscount.com/catalog/symbol/">symbol
 scanners</a> are able to read incomprehensible <a
 href="http://www.fda.gov/oc/initiatives/barcode-sadr/fs-barcode.html">code</a>
 so that we can understand it, and <a
 href="http://www.barcodediscount.com/catalog/zebra/">zebra printers</a> can
 print out the results.
<br><hr></p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/general-programming/six-language-independent-ways-to-write-better-code/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>
