<?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; C++ Programming</title>
	<atom:link href="http://www.learncpp.com/category/cpp-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>17.7 &#8212; std::string inserting</title>
		<link>http://www.learncpp.com/cpp-tutorial/17-7-stdstring-inserting/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/17-7-stdstring-inserting/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 05:50:27 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>
		<category><![CDATA[C++ Tutorial]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=462</guid>
		<description><![CDATA[Inserting
Inserting characters into an existing string can be done via the insert() function.



string&#038; string::insert (size_type index, const string&#038; str)
string&#038; string::insert (size_type index, const char* str)

Both functions insert the characters of str into the string at index
Both function return *this so they can be &#8220;chained&#8221;.
Both functions throw out_of_range if index is invalid
Both functions throw a length_error [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Inserting</strong></p>
<p>Inserting characters into an existing string can be done via the insert() function.</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::insert (size_type index, const string&#038; str)</b><br />
<b>string&#038; string::insert (size_type index, const char* str)</b></p>
<ul>
<li>Both functions insert the characters of str into the string at index
<li>Both function return *this so they can be &#8220;chained&#8221;.
<li>Both functions throw out_of_range if index is invalid
<li>Both functions throw a length_error exception if the result exceeds the maximum number of characters.
<li>In the C-style string version, str must not be NULL.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;aaaa&quot;);
cout &lt;&lt; sString &lt;&lt; endl;

sString.insert(2, string(&quot;bbbb&quot;));
cout &lt;&lt; sString &lt;&lt; endl;

sString.insert(4, &quot;cccc&quot;);
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
aaaa
aabbbbaa
aabbccccbbaa
</pre>
</td>
</tr>
</table>
<p></p>
<p>Here&#8217;s a crazy version of insert() that allows you to insert a substring into a string at an arbitrary index:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::insert (size_type index, const string&#038; str, size_type startindex, size_type num)</b></p>
<ul>
<li>This function inserts num characters str, starting from startindex, into the string at index.
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws an out_of_range if index or startindex is out of bounds
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;aaaa&quot;);

const string sInsert(&quot;01234567&quot;);
sString.insert(2, sInsert, 3, 4); // insert substring of sInsert from index [3,7) into sString at index 2
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
aa3456aa
</pre>
</td>
</tr>
</table>
<p></p>
<p>There is a flavor of insert() that inserts the first portion of a C-style string:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::insert(size_type index, const char* str, size_type len)</b></p>
<ul>
<li>Inserts len characters of str into the string at index
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws an out_of_range exception if the index is invalid
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
<li>Ignores special characters (such as &#8216;\0&#8242;)
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;aaaa&quot;);

sString.insert(2, &quot;bcdef&quot;, 3);
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
aabcdaa
</pre>
</td>
</tr>
</table>
<p></p>
<p>There&#8217;s also a flavor of insert() that inserts the same character multiple times:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::insert(size_type index, size_type num, char c)</b></p>
<ul>
<li>Inserts num instances of char c into the string at index
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws an out_of_range exception if the index is invalid
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;aaaa&quot;);

sString.insert(2, 4, 'c');
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
aaccccaa
</pre>
</td>
</tr>
</table>
<p></p>
<p>And finally, the insert() function also has three different versions that use iterators:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>void insert(iterator it, size_type num, char c)</b><br />
<b>iterator string::insert(iterator it, char c)</b><br />
<b>void string::insert(iterator it, InputIterator begin, InputIterator end)</b></p>
<ul>
<li>The first function inserts num instances of the character c before the iterator it.
<li>The second inserts a single character c before the iterator it, and returns an iterator to the position of the character inserted.
<li>The third inserts all characters between [begin,end) before the iterator it.
<li>All functions throw a length_error exception if the result exceeds the maximum number of characters.
</ul>
</td>
</tr>
</table>
<p></p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle></a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter17" 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-programming/17-6-stdstring-appending/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 17.6 &#8212; std::string appending</a>
</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/17-7-stdstring-inserting/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>17.6 &#8212; std::string appending</title>
		<link>http://www.learncpp.com/cpp-tutorial/17-6-stdstring-appending/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/17-6-stdstring-appending/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 23:35:17 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>
		<category><![CDATA[C++ Tutorial]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=454</guid>
		<description><![CDATA[Appending
Appending strings to the end of an existing string is easy using either operator+=, append(), or push_back() function.



string&#038; string::operator+= (const string&#038; str)
string&#038; string::append (const string&#038; str)


Both functions append the characters of str to the string.
Both function return *this so they can be &#8220;chained&#8221;.
Both functions throw a length_error exception if the result exceeds the maximum number [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Appending</strong></p>
<p>Appending strings to the end of an existing string is easy using either operator+=, append(), or push_back() function.</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::operator+= (const string&#038; str)</b><br />
<b>string&#038; string::append (const string&#038; str)</b><br />
</p>
<ul>
<li>Both functions append the characters of str to the string.
<li>Both function return *this so they can be &#8220;chained&#8221;.
<li>Both functions throw a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;one&quot;);

sString += string(&quot; two&quot;);

string sThree(&quot; three&quot;);
sString.append(sThree);

cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
one two three
</pre>
</td>
</tr>
</table>
<p></p>
<p>There&#8217;s also a flavor of append() that can append a substring:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::append (const string&#038; str, size_type index, size_type num)</b></p>
<ul>
<li>This function appends num characters from str, starting at index, to the string.
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws an out_of_range if index is out of bounds
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;one &quot;);

const string sTemp(&quot;twothreefour&quot;);
sString.append(sTemp, 3, 5); // append substring of sTemp starting at index 3 of length 5
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
one three
</pre>
</td>
</tr>
</table>
<p></p>
<p>Operator+= and append() also have versions that work on C-style strings:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::operator+= (const char* str)</b><br />
<b>string&#038; string::append (const char* str)</b><br />
</p>
<ul>
<li>Both functions append the characters of str to the string.
<li>Both function return *this so they can be &#8220;chained&#8221;.
<li>Both functions throw a length_error exception if the result exceeds the maximum number of characters.
<li>str should not be NULL.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;one&quot;);

sString += &quot; two&quot;;
sString.append(&quot; three&quot;);
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
one two three
</pre>
</td>
</tr>
</table>
<p></p>
<p>There is an additional flavor of append() that works on C-style strings:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::append (const char* str, size_type len)</b><br />
</p>
<ul>
<li>Appends the first len characters of str to the string.
<li>Returns *this so they can be &#8220;chained&#8221;.
<li>Throw a length_error exception if the result exceeds the maximum number of characters.
<li>Ignores special characters (including &#8216;\0&#8242;)
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;one&quot;);

sString.append(&quot;threefour&quot;, 5);
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
one three
</pre>
<p>This function is dangerous and its use is not recommended.</p>
</td>
</tr>
</table>
<p></p>
<p>There is also a set of functions that append characters.  Note that the name of the non-operator function to append a character is push_back(), not append()!</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::operator+= (char c)</b><br />
<b>void string::push_back (char c)</b><br />
</p>
<ul>
<li>Both functions append the the character c to the string.
<li>Operator += returns *this so it can be &#8220;chained&#8221;.
<li>Both functions throw a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;one&quot;);

sString += ' ';
sString.append('2');
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
one 2
</pre>
<p>Now you might be wondering why the name of the function is push_back() and not append().  This follows a naming convention used for stacks, where push_back() is the function that adds a single item to the end of the stack.  If you envision a string as a stack of characters, using push_back() to add a single character to the end makes sense.  However, the lack of an append() function is inconsistent in my view!</p>
</td>
</tr>
</table>
<p></p>
<p>It turns out there is an append() function for characters, that looks like this:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::append (size_type num, char c)</b><br />
</p>
<ul>
<li>Adds num occurrences of the character c to the string
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString(&quot;aaa&quot;);

sString.append(4, 'b');
cout &lt;&lt; sString &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
aaabbbb
</pre>
</td>
</tr>
</table>
<p></p>
<p>There&#8217;s one final flavor of append() that you won&#8217;t understand unless you know what iterators are.  If you&#8217;re not familiar with iterators, you can ignore this function.</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::append (InputIterator start, InputIterator end)</b><br />
</p>
<ul>
<li>Appends all characters from the range [start, end) (including start up to but not including end)
<li>Returns *this so it can be &#8220;chained&#8221;.
<li>Throws a length_error exception if the result exceeds the maximum number of characters.
</ul>
</td>
</tr>
</table>
<p></p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/17-7-stdstring-inserting/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle>17.7 &#8212; std::string inserting</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter17" 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-programming/17-5-stdstring-assignment-and-swapping/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 17.5 &#8212; std::string assignment and swapping</a>
</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/17-6-stdstring-appending/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>17.5 &#8212; std::string assignment and swapping</title>
		<link>http://www.learncpp.com/cpp-programming/17-5-stdstring-assignment-and-swapping/</link>
		<comments>http://www.learncpp.com/cpp-programming/17-5-stdstring-assignment-and-swapping/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 22:21:25 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=444</guid>
		<description><![CDATA[String assignment
The easiest way to assign a value to a string is to the use the overloaded operator= function.  There is also an assign() member function that duplicates some of this functionality.



string&#038; string::operator= (const string&#038; str)
string&#038; string::assign (const string&#038; str)
string&#038; string::operator= (const char* str)
string&#038; string::assign (const char* str)
string&#038; string::operator= (char c)


These functions assign values [...]]]></description>
			<content:encoded><![CDATA[<p><strong>String assignment</strong></p>
<p>The easiest way to assign a value to a string is to the use the overloaded operator= function.  There is also an assign() member function that duplicates some of this functionality.</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::operator= (const string&#038; str)</b><br />
<b>string&#038; string::assign (const string&#038; str)</b><br />
<b>string&#038; string::operator= (const char* str)</b><br />
<b>string&#038; string::assign (const char* str)</b><br />
<b>string&#038; string::operator= (char c)</b><br />
</p>
<ul>
<li>These functions assign values of various types to the string.
<li>These functions return *this so they can be &#8220;chained&#8221;.
<li>Note that there is no assign() function that takes a single char.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sString;

// Assign a string value
sString = string(&quot;One&quot;);
cout &lt;&lt; sString &lt;&lt; endl;

const string sTwo(&quot;Two&quot;);
sString.assign(sTwo);
cout &lt;&lt; sString &lt;&lt; endl;

// Assign a C-style string
sString = &quot;Three&quot;;
cout &lt;&lt; sString &lt;&lt; endl;

sString.assign(&quot;Four&quot;);
cout &lt;&lt; sString &lt;&lt; endl;

// Assign a char
sString = '5';
cout &lt;&lt; sString &lt;&lt; endl;

// Chain assignment
string sOther;
sString = sOther = &quot;Six&quot;;
cout &lt;&lt; sString &lt;&lt; &quot; &quot; &lt;&lt; sOther &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
One
Two
Three
Four
5
Six Six
</pre>
</td>
</tr>
</table>
<p></p>
<p>The assign() member function also comes in a few other flavors:</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::assign (const string&#038; str, size_type index, size_type len)</b></p>
<ul>
<li>Assigns a substring of str, starting from index, and of length len
<li>Throws an out_of_range exception if the index is out of bounds
<li>Returns *this so it can be &#8220;chained&#8221;.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
const string sSource(&quot;abcdefg&quot;);
string sDest;

sDest.assign(sSource, 2, 4); // assign a substring of source from index 2 of length 4
cout &lt;&lt; sDest &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
cdef
</pre>
</td>
</tr>
</table>
<p></p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::assign (const char* chars, size_type len)</b></p>
<ul>
<li>Assigns len characters from the C-style array chars
<li>Ignores special characters (including &#8216;\0&#8242;)
<li>Throws an length_error exception if the result exceeds the maximum number of characters
<li>Returns *this so it can be &#8220;chained&#8221;.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sDest;

sDest.assign(&quot;abcdefg&quot;, 4);
cout &lt;&lt; sDest &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
abcd
</pre>
<p>This function is potentially dangerous and it&#8217;s use is not recommended.</p>
</td>
</tr>
</table>
<p></p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>string&#038; string::assign (size_type len, char c)</b></p>
<ul>
<li>Assigns len occurrences of the character c
<li>Throws an length_error exception if the result exceeds the maximum number of characters
<li>Returns *this so it can be &#8220;chained&#8221;.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sDest;

sDest.assign(4, 'g');
cout &lt;&lt; sDest &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
gggg
</pre>
</td>
</tr>
</table>
<p></p>
<p><strong>Swapping</strong></p>
<p>If you have two strings and want to swap their values, there are two functions both named swap() that you can use.</p>
<table border=1 cellspacing=0 cellpadding=3 width=100%>
<tr>
<td>
<b>void string::swap (string &#038;str)</b><br />
<b>void swap (string &#038;str1, string &#038;str2)</b></p>
<ul>
<li>Both functions swap the value of the two strings.  The member function swaps *this and str, the global function swaps str1 and str2.
<li>These functions are efficient and should be used instead of assignments to perform a string swap.
</ul>
<p>Sample code:</p>
<pre class="brush: cpp;">
string sStr1(&quot;red&quot;);
string sStr2(&quot;blue);

cout &lt;&lt; sStr1 &lt;&lt; &quot; &quot; &lt;&lt; sStr2 &lt;&lt; endl;
swap(sStr1, sStr2);
cout &lt;&lt; sStr1 &lt;&lt; &quot; &quot; &lt;&lt; sStr2 &lt;&lt; endl;
sStr1.swap(sStr2);
cout &lt;&lt; sStr1 &lt;&lt; &quot; &quot; &lt;&lt; sStr2 &lt;&lt; endl;
</pre>
<p>Output:</p>
<pre>
red blue
blue red
red blue
</pre>
</td>
</tr>
</table>
<p></p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/uncategorized/17-6-stdstring-appending/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 17.6 &#8212; std::string appending</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter17" 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/17-4-stdstring-character-access-and-conversion-to-c-style-arrays/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 17.4 &#8212; std::string character access and conversion to c-style strings</a>
</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-programming/17-5-stdstring-assignment-and-swapping/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>13.2 &#8212; Input with istream</title>
		<link>http://www.learncpp.com/cpp-tutorial/132-input-with-istream/</link>
		<comments>http://www.learncpp.com/cpp-tutorial/132-input-with-istream/#comments</comments>
		<pubDate>Wed, 05 Mar 2008 00:09:23 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>
		<category><![CDATA[C++ Tutorial]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/132-input/</guid>
		<description><![CDATA[The iostream library is fairly complex &#8212; so we will not be able to cover it in it&#8217;s entirety in these tutorials.  However, we will show you the most commonly used functionality.  In this section, we will look at various aspects of the input class (istream).
Note: All of the I/O functionality in this [...]]]></description>
			<content:encoded><![CDATA[<p>The iostream library is fairly complex &#8212; so we will not be able to cover it in it&#8217;s entirety in these tutorials.  However, we will show you the most commonly used functionality.  In this section, we will look at various aspects of the input class (istream).</p>
<p>Note: All of the I/O functionality in this lesson lives in the std namespace.  That means all I/O objects and functions either have to be prefixed with &#8220;std::&#8221;, or the &#8220;using namespace std;&#8221; statement has to be used.</p>
<p><strong>The extraction operator</strong></p>
<p>As seen in many lessons now, we can use the extraction operator (>>) to read information from an input stream.  C++ has predefined extraction operations for all of the built-in data types, and you&#8217;ve already seen how you can <a href="http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/">overload the extraction operator</a> for your own classes.</p>
<p>When reading strings, one common problem with the extraction operator is how to keep the input from overflowing your buffer.  Given the following example:</p>
<pre class="brush: cpp;">
char buf[10];
cin &gt;&gt; buf;
</pre>
<p>what happens if the user enters 18 characters?  The buffer overflows, and bad stuff happens.  Generally speaking, it&#8217;s a bad idea to make any assumption about how many characters your user will enter.</p>
<p>One way to handle this problem is through use of manipulators.  A <strong>manipulator</strong> is an object that is used to modify a stream when applied with the extraction (>>) or insertion (<<) operators.  One manipulator you have already worked with extensively is "endl", which both prints a newline character and flushes any buffered output.</p>
<p>C++ provides a manipulator known as <strong>setw</strong> (in the iomanip.h header) that can be used to limit the number of characters read in from a stream.  To use setw(), simply provide the maximum number of characters to read as a parameter, and insert it into your input statement like such:</p>
<pre class="brush: cpp;">
#include &lt;iomanip.h&gt;
char buf[10];
cin &gt;&gt; setw(10) &gt;&gt; buf;
</pre>
<p>This program will now only read the first 9 characters out of the stream (leaving room for a terminator).  Any remaining characters will be left in the stream until the next extraction.</p>
<p><strong>Extraction and whitespace</strong></p>
<p>The one thing that we have omitted to mention so far is that the extraction operator works with &#8220;formatted&#8221; data &#8212; that is, it skips whitespace (blanks, tabs, and newlines).</p>
<p>Take a look at the following program:</p>
<pre class="brush: cpp;">
int main()
{
    char ch;
    while (cin &gt;&gt; ch)
        cout &lt;&lt; ch;

    return 0;
}
</pre>
<p>When the user inputs the following:</p>
<pre>
Hello my name is Alex
</pre>
<p>The insertion operator skips the spaces and the newline.  Consequently, the output is:</p>
<pre>
HellomynameisAlex
</pre>
<p>Oftentimes, you&#8217;ll want to get user input but not discard whitespace.  To do this, the istream class provides many functions that can be used for this purpose.</p>
<p>One of the most useful is the <strong>get()</strong> function, which simply gets a character from the input stream.  Here&#8217;s the same program as above using get():</p>
<pre class="brush: cpp;">
int main()
{
    char ch;
    while (cin.get(ch))
        cout &lt;&lt; ch;

    return 0;
}
</pre>
<p>Now when we use the input:</p>
<pre>
Hello my name is Alex
</pre>
<p>The output is:</p>
<pre>
Hello my name is Alex
</pre>
<p>get() also has a string version that takes a maximum number of characters to read:</p>
<pre class="brush: cpp;">
int main()
{
    char strBuf[11];
    cin.get(strBuf, 11);
    cout &lt;&lt; strBuf &lt;&lt; endl;

    return 0;
}
</pre>
<p>If we input:</p>
<pre>
Hello my name is Alex
</pre>
<p>The output is:</p>
<pre>
Hello my n
</pre>
<p>Note that we only read<noscript>Convert mp3 to <a href="http://www.qualidade-toques.com/mais-populares-eua-baixar-toques-para-celular.html">baixar toques para celular</a> gospel gratuito, pe?as para toques gratis para celulares Nokia que possuem o compositor Nokia.</noscript> the first 10 characters (we had to leave one character for a terminator).  The remaining characters were left in the input stream.</p>
<p>One important thing to note about get() is that it does not read in a newline character!  This can cause some unexpected results:</p>
<pre class="brush: cpp;">
int main()
{
    char strBuf[11];
    // Read up to 10 characters
    cin.get(strBuf, 11);
    cout &lt;&lt; strBuf &lt;&lt; endl;

    // Read up to 10 more characters
    cin.get(strBuf, 11);
    cout &lt;&lt; strBuf &lt;&lt; endl;
    return 0;
}
</pre>
<p>If the user enters:</p>
<pre>
Hello!
</pre>
<p>The program will print:</p>
<pre>
Hello!
</pre>
<p>and then terminate!  Why didn&#8217;t it ask for 10 more characters?  The answer is because the first get() read up to the newline and then stopped.  The second get() saw there was still input in the cin stream and tried to read it.  But the first character was the newline, so it stopped immediately.</p>
<p>Consequently, there is another function called <strong>getline()</strong> that works exactly like get() but reads the newline as well.</p>
<pre class="brush: cpp;">
int main()
{
    char strBuf[11];
    // Read up to 10 characters
    cin.getline(strBuf, 11);
    cout &lt;&lt; strBuf &lt;&lt; endl;

    // Read up to 10 more characters
    cin.getline(strBuf, 11);
    cout &lt;&lt; strBuf &lt;&lt; endl;
    return 0;
}
</pre>
<p>This code will perform as you expect, even if the user enters a string with a newline in it.</p>
<p>If you need to know how many character were extracted by the last call of getline(), use <strong>gcount()</strong>:</p>
<pre class="brush: cpp;">
int main()
{
    char strBuf[100];
    cin.getline(strBuf, 100);
    cout &lt;&lt; strBuf &lt;&lt; endl;
    cout &lt;&lt; cin.gcount() &lt;&lt; &quot; characters were read&quot; &lt;&lt; endl;

    return 0;
}
</pre>
<p><strong>A special version of getline() for std::string</strong></p>
<p>There is a special version of getline() that lives outside the istream class that is used for reading in variables of type std::string.  This special version is not a member of either ostream nor istream, and is included in the string header.  Here is an example of it&#8217;s use:</p>
<pre class="brush: cpp;">
#include &lt;string&gt;
#include &lt;iostream&gt;

int main()
{
    using namespace std;
    string strBuf;
    getline(cin, strBuf);
    cout &lt;&lt; strBuf &lt;&lt; endl;

    return 0;
}
</pre>
<p><strong>A<noscript>Beruhmte <a href="http://www.kostenlose-casino.de/downloaden-sie-casino-net-spiel.html">casino net</a>.</noscript> few more useful istream functions</strong></p>
<p>There are a few more useful input functions that you might want to make use of:</p>
<p><strong>ignore()</strong> discards the first character in the stream.<br />
<strong>ignore(int nCount)</strong> discards the first nCount characters.<br />
<strong>peek()</strong> allows you to read a character from the stream without removing it from the stream.<br />
<strong>unget()</strong> returns the last character read back into the stream so it can be read again by the next call.<br />
<strong>putback(char ch)</strong> allows you to put a character of your choice back into the stream to be read by the next call.</p>
<p>istream contains many other functions and variants of the above mentioned functions that may be useful, depending on what you need to do.  However, those topics are really more suited for a tutorial or book focusing on the standard library (such as the excellent <a href="http://astore.amazon.com/lc0a-20/detail/0201379260/102-6574246-5645752">&#8220;The C++ Standard Template Library&#8221;</a> by Nicolai M. Josuttis).</p>
<table border=0 cellpadding=3>
<tr>
<td>
        <a href="http://www.learncpp.com/cpp-tutorial/133-output-with-ostream-and-ios/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/next.png" align=middle> 13.3 &#8212; Output with ostream and ios</a>
</td>
</tr>
<tr>
<td>
        <a href="http://www.learncpp.com/#Chapter13" 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/131-input-and-output-io-streams/" style="text-decoration:none"><img src="http://www.learncpp.com/images/CppTutorial/prev.png" align=middle> 13.1 &#8212; Input and output (I/O) streams</a>
</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-tutorial/132-input-with-istream/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Eight C++ programming mistakes the compiler won&#8217;t catch</title>
		<link>http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/</link>
		<comments>http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/#comments</comments>
		<pubDate>Mon, 02 Jul 2007 17:29:09 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/</guid>
		<description><![CDATA[





C++ is a complex language, full of subtle traps for the unwary. There is an almost infinite number of ways to screw things up.  Fortunately, modern compilers are pretty good at detecting a large number of these cases and notifying the programmer via compile errors or warnings.  Ultimately, any error that is compiler-detectable [...]]]></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 />
C++ is a complex language, full of subtle traps for the unwary. There is an almost infinite number of ways to screw things up.  Fortunately, modern compilers are pretty good at detecting a large number of these cases and notifying the programmer via compile errors or warnings.  Ultimately, any error that is compiler-detectable becomes a non-issue if properly handled, as it will be caught and fixed before the program leaves development.  At worst, a compiler-detectable error results in lost time while the programmer searches for a solution or workaround.</p>
<p>The dangerous errors are the ones that compilers are <em>unable</em> to detect.  These errors are much less likely to be noticed, and can cause severe consequences such as incorrect outputs, corrupted data, and/or program crashes.  As the size of a programming project increases, the complexity of the logic and large number of paths of execution can help obscure these bugs, causing them to appear only intermittently, making them particularly hard to track down and debug.  Although this list may be mostly review to experienced programmers, the consequences of making one of these errors is also amplified due to the scale and commercial nature of the projects experienced programmers tend to work on.  </p>
<p>These examples were all tested using Visual Studio 2005 Express using the default warning level.  Your results may vary on other compilers.  <strong>I highly recommend all programmers use the highest warning level possible!</strong>.  Some items that may not be flagged as a potential problem at the default warning level may be caught at the highest warning level!</p>
<p>(Note: This article is part 1 in an intended series of articles)</p>
<p><br clear="all"></p>
<hr />
<h3>1) Uninitialized variables</h3>
<p>Uninitialized variables are one of the most devious mistakes commonly made in C++.  Memory allocated to a variable in C++ is not cleared or zeroed upon allocation.  Consequently, an uninitialized variable will have some value, but there is no way to predict what that value will actually be.  Furthermore, the value of the variable may change each time the program is executed.  This can result in intermittent problems, which are particularly hard to track down.  Consider the following snippet:</p>
<pre>
if (bValue)
    // do A
else
    // do B
</pre>
<p>If bValue is uninitialized, it could evaluate to either true or false, and either branch could be taken.</p>
<p>In some basic cases, the compiler will be able to inform you of an uninitialized variable.  The following causes a compiler warning on most compilers:</p>
<pre>
int foo()
{
int nX;
return nX;
}
</pre>
<p>However, other simple cases generally do not produce warnings:</p>
<pre>
void increment(int &amp;nValue)
{
    ++nValue;
}

int foo()
{
int nX;
increment(nX);
return nX;
}
</pre>
<p>The above may not produce a warning because the compiler typically doesn&#8217;t keep track of whether increment() assigns a value to nValue.</p>
<p>Uninitialized variables are even more likely to appear in classes, where member declaration are generally separated by from the constructor implementation:</p>
<pre>
class Foo
{
private:
    int m_nValue;

public:
    Foo();
    int GetValue() { return m_bValue; }
};

Foo::Foo()
{
    // Oops, we forget to initialize m_nValue
}

int main()
{
    Foo cFoo;
    if (cFoo.GetValue() &gt; 0)
        // do something
    else
        // do something else
}
</pre>
<p>Note that m_nValue is never initialized.  Consequently, GetValue() returns a junk value, and either branch may be executed.</p>
<p>New programmers often make the following mistake when declaring multiple variables:</p>
<pre>
int nValue1, nValue2 = 5;
</pre>
<p>The assumption being made here is that 5 is assigned to both nValue1 and nValue2, when in fact the value of 5 is only assigned to nValue2, and nValue1 is uninitialized.</p>
<p>Because uninitialized variables can evaluate to any value, which can cause the program to exhibit different behavior each time it is run, problems caused by uninitialized variables are particularly hard to find.  One run, the program may work fine.  The next time, it may crash.  The after that, it may produce the wrong output.</p>
<p>To compound problems finding uninitialized variables, variable declared when running the program in a debugger are typically zeroed.  This means your program may work fine every time when run in a debugger, but crash intermittently in release mode!  If this is the case, an uninitialized variable is often the root of your problem.</p>
<hr />
<h3>2) Integer division</h3>
<p>Most binary operators in C++ require both operands to be the same type.  If the operands are of different types, one of the operands is promoted to match the type of the other.</p>
<p>In C++, the division operator can be thought of as two different operators: one that works on integer operands, and one that works on floating point operands.  If the operands are of a floating point type, the division operator will return a floating point value:</p>
<pre>
float fX = 7;
float fY = 2;
float fValue = fX / fY; // fValue = 3.5
</pre>
<p>If the operands are of an integer type, the division operator will drop any faction and return an integer value:</p>
<pre>
int nX = 7;
int nY = 2;
int nValue = nX / nY; // nValue = 3
</pre>
<p>If one operand is an integer, and the other is a floating point value, the integer value will be promoted to a floating point type:</p>
<pre>
float fX = 7.0;
int nY = 2;
float fValue = fX / nY;

// nY is promoted to float, floating point division used
// fValue = 3.5
</pre>
<p>Many new programmers attempt to do the following:</p>
<pre>
int nX = 7;
int nY = 2;
float fValue = nX / nY;  // fValue = 3 (not 3.5!)
</pre>
<p>The underlying assumption here is that nX / nY will result in a floating point division because the result is being assigned to a floating point value.  However, this is not the case.  nX / nY is evaluated first, resulting in an integer value, which is then promoted to a float and assigned to fValue.  However, by that point, the fraction has already been lost.</p>
<p>In order to force two integers to use floating point division, one of the values should be cast to a floating point value:</p>
<pre>
int nX = 7;
int nY = 2;
float fValue = static_cast&lt;float&gt;(nX) / nY; // fValue = 3.5
</pre>
<p>Because nX is being explicitly cast to a float, nY will be implicitly promoted to a float, which will cause the division operator to perform floating point division, resulting in a value of 3.5.</p>
<p>It is often hard to tell at a glance whether a given division operation is performing integer or floating point division:</p>
<pre>
z = x / y; // is this integer or floating point division?
</pre>
<p>However, using Hungarian Notation can help disambiguate the case and help prevent mistakes:</p>
<pre>
int nZ = nX / nY; // integer division
double dZ = dX / dY; // floating point division
</pre>
<p>One other interesting issue with integer division is that C++ does not define how to truncate the result when one operand is negative.  Consequently, the compiler is free to truncate up or down!  For example, -5 / 2 can evaluate to either -3 or -2, depending on whether the compiler rounds down or rounds toward 0.  Most modern compilers round towards 0.</p>
<hr />
<h3>3) = vs ==</h3>
<p>This one is an oldie but a goodie.  Many beginning C++ programmers confuse the meaning of the assignment operator (=) with the equality operator (==).  But even programmers who know the difference can make a typo that will have unintended results:</p>
<pre>
// if nValue is 0, return 1, otherwise return nValue
int foo(int nValue)
{
    if (nValue = 0) // TYPO!
        return 1;
    else
        return nValue;
}

int main()
{
    std::cout &lt;&lt; foo(0) &lt;&lt; std::endl;
    std::cout &lt;&lt; foo(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; foo(2) &lt;&lt; std::endl;

    return 0;
}
</pre>
<p>Function foo() is intended to return 1 if nValue is 0, otherwise return nValue.  But due to inadvertently using the assignment operator instead of the equality operator, the program produces an unexpected result:</p>
<pre>
0
0
0
</pre>
<p>When the <em>if statement</em> in foo() is evaluated, nValue is assigned the value of 0.  <code>if (nValue = 0)</code> evaluates the same way that <code>nValue = 0; if (nValue)</code> evaluates.  Consequently, the if condition is false, which causes the else statement to return nValue, which was just assigned the value of 0!</p>
<p>Consequently, this function always returns 0.</p>
<p>Running a modern compiler at the highest warning level will cause it to issue a warning when an assignment is used in a conditional statement, or a note that the statement does nothing when an equality test is used instead of an assignment outside of a conditional.  This is one issue that is essentially fixable &#8212; if you use the higher warning levels.</p>
<hr />
<h3>4) Mixing signed and unsigned values</h3>
<p>As mentioned in the section on integer division, most binary operators in C++ require both operands to be the same type.  If the operands are of different types, one of the operands is promoted to match the type of the other.</p>
<p>This can lead to some very unexpected results when mixing signed and unsigned values!  Consider the following case:</p>
<pre>
cout &lt;&lt; 10 - 15u; // 15u is unsigned
</pre>
<p>One would expect the answer to be -5.  However, because 10 is an signed integer and 15 is an unsigned integer, the type promotion rules come into effect here.  The hierarchy used for type promotion in C++ looks like this:</p>
<p>long double (highest)<br />
double<br />
float<br />
unsigned long int<br />
long int<br />
unsigned int<br />
int (lowest)</p>
<p>Because the int operand is considered lower than the unsigned int operand, the int is promoted to an unsigned int.  Fortunately, 10 is already a positive number, so the promotion does not cause our number to be interpreted any differently.</p>
<p>Thus, we effectively have:</p>
<pre>
cout &lt;&lt; 10u - 15u
</pre>
<p>Here&#8217;s where the tricky part happens.  Because both variables are unsigned integers, the result of the operation is also an unsigned integer!  10u &#8211; 15u = -5u.  But unsigned variables can not hold negative numbers, and thus the -5 is interpreted as 4,294,967,291 (assuming 32 bit integers).</p>
<p>Consequently, the following program:</p>
<pre>
cout &lt;&lt; 10 - 15u; // 15u is unsigned
</pre>
<p>prints 4,294,967,291, not -5.</p>
<p>This situation can come up in more obscure forms:</p>
<pre>
int nX;
unsigned int nY;

if (nX - nY &lt; 0)
    // do something
</pre>
<p>Due to the type conversion, this if statement will always evaluate to false, which is clearly not what the programmer intends!</p>
<hr />
<h3>5) delete vs. delete[]</h3>
<p>Many C++ programmers forget that there are actually two forms of the both the new and delete operators: a scalar version, and an array version.</p>
<p>Operator new is used to allocate scalar (non-array) data on the heap.  If the object being allocated is a class type, the object&#8217;s constructor is called.</p>
<pre>
Foo *pScalar = new Foo;
</pre>
<p>The delete operator is used to destroy a scalar object that has been allocated using the new operator.  If the object being destroyed is a class type, the object&#8217;s destructor is called.</p>
<pre>
delete pScalar;
</pre>
<p>Now consider the following snippet:</p>
<pre>
Foo *pArray = new Foo[10];
</pre>
<p>This snippet allocates an array of 10 Foo.  Because the subscript [10] is placed after the int type specifier, many C++ programmers do not realize that operator new[] is being called to do the array allocation instead of operator new.  Operator new[] ensures that the constructor is called for each object being constructed.</p>
<p>Conversely, to delete an array, the delete[] operator should be used:</p>
<pre>
delete[] pArray;
</pre>
<p>This ensures that the destructor for each object in the array is called.</p>
<p>If the delete operator is used on an array, only the first object will be destructed, and heap corruption can result!</p>
<hr />
<h3>6) Side effects in compound expressions or function calls</h3>
<p>A side effect is a result of an operator, expression, statement, or function that persists even after the operator, expression, statement, or function has finished being evaluated.</p>
<p>Side effects can often be useful:</p>
<pre>
x = 5;
</pre>
<p>The assignment operator has the side effect of changing the value of x permanently.  Other C++ operators with useful side effects include *=, /=, %=, +=, -=, <<=, >>=, &#038;=, |=, ^=, and the infamous ++ and &#8212; operators.</p>
<p>However, there are several places in C++ where the order of operations is undefined, and these can lead to inconsistent behavior.  For example:</p>
<pre>
void multiply(int x, int y)
{
    using namespace std;
    cout &lt;&lt; x * y &lt;&lt; endl;
}

int main()
{
    int x = 5;
    std::cout &lt;&lt; multiply(x, ++x);
}
</pre>
<p>Because the order of evaluation of the function parameters for multiply() is undefined, this could print 30 or 36, depending on whether x or ++x is evaluated first.</p>
<p>A slightly stranger example involving operators:</p>
<pre>
int foo(int x)
{
return x;
}

int main()
{
    int x = 5;
    std::cout &lt;&lt; foo(x) * foo(++x);
}
</pre>
<p>Because the order of evaluation of the operands of C++ operators is undefined (for most operators &#8212; there are a few exceptions), this could also print 30 or 36, depending on whether the left or right operand is evaluated first.</p>
<p>Also consider the following compound expression:</p>
<pre>
if (x == 1 &amp;&amp; ++y == 2)
    // do something
</pre>
<p>The intent of the programmer is probably to say &#8220;if x is 1 and the pre-incremented value of y is 2, then do something&#8221;.  However, if x does not equal 1, C++ uses short-circuit evaluation, which means that ++y never gets evaluated! Thus, y will only be incremented if x evaluates to 1, which is probably not what the programmer intended!</p>
<p>A good rule of thumb is to put any operator that causes a side effect in it&#8217;s own statement.</p>
<hr />
<h3>7) Switch statements without break</h3>
<p>Another classic mistake that new programmers make is forgetting to use break to end a switch block:</p>
<pre>
switch (nValue)
{
    case 1: eColor = Color::BLUE;
    case 2: eColor = Color::PURPLE;
    case 3: eColor = Color::GREEN;
    default: eColor = Color::RED;
}
</pre>
<p>When the switch expression evaluates to the same value as the case label expression, execution starts at the matching case statement.   Execution then continues until either the end of the switch block is reached, or a return, goto, or break statement is executed.  Any other labels are ignored!</p>
<p>Consider what happens if nValue is 1 in the above program.  Case 1 matches, so eColor is set to Color::BLUE.  Evaluation proceeds to the next statement, which sets eColor to Color::PURPLE.  The next statement sets it to Color::GREEN.  And finally, it gets set to Color::RED.</p>
<p>In fact, this snippet ends up setting eColor to COLOR::RED no matter what the value of nValue is!</p>
<p>The correct way to write the above program is:</p>
<pre>
switch (nValue)
{
    case 1: eColor = Color::BLUE;  break;
    case 2: eColor = Color::PURPLE;  break;
    case 3: eColor = Color::GREEN;  break;
    default: eColor = Color::RED;  break;
}
</pre>
<p>The break terminates the case statement, thus causing eColor to retain the value that the programmer intended.</p>
<p>Although this is very basic switch/case logic, it is very easy to miss a break statement and end up with inadvertent fall-through.  </p>
<hr />
<h3>8) Calling virtual functions in constructors</h3>
<p>Consider the following program:</p>
<pre>
class Base
{
private:
    int m_nID;
public:
    Base()
    {
        m_nID = ClassID();
    }

    // ClassID returns a class-specific ID number
    virtual int ClassID() { return 1; }

    int GetID() { return m_nID; }
};

class Derived: public Base
{
public:
    Derived()
    {
    }

    virtual int ClassID() { return 2; }
};

int main()
{
    Derived cDerived;
    cout &lt;&lt; cDerived.GetID(); // prints 1, not 2!
    return 0;
}
</pre>
<p>In this program, the programmer has called a virtual function inside the constructor of a base class, expecting it to resolve to Derived::ClassID().  It doesn&#8217;t &#8212; and consequently, the program prints 1 instead of 2.</p>
<p>When an class that has been derived from a base classes is instantiated, the base class object is constructed before the derived class object.  This is done because the derived class members may be dependent upon members of the base class already being initialized.  Consequently, when the base object constructor is being executed, there is no derived object!  It hasn&#8217;t been created yet.  Thus, any call to a virtual function can only resolve to the level of the base class, not the derived class. </p>
<p>As pertains to this example, when the Base portion of cDerived is being constructed, the Derived portion does not exist yet.  Thus, the function call to ClassID() resolves to Base::ClassID() (not Derived::ClassID()), which sets m_nID to 1.</p>
<p>Once the Derived portion of cDerived has been constructed, any calls to ClassID() on this object will resolve to Derived::ClassID() as anticipated.</p>
<p>Note that some other programming languages (such as C# and Java) will resolve virtual function calls to the most derived class even if the derived class has not been initialized yet!  C++ differs in this regard, and does so for the programmer&#8217;s safety.  That is not to say one way is necessarily better than the other, but merely to denote that different languages may have different behaviors.</p>
<hr />
<h3>Conclusion</h3>
<p>As this is the first article in this series, I thought it appropriate to start with some of the more basic issues that new programmers will encounter.  Future articles in this series will tackle programming mistakes of an increasingly complex nature.  </p>
<p>Regardless of a programmer&#8217;s experience level, mistakes happens, whether through lack of knowledge, a typo, or general carelessness.  Being aware of which issues are <em>most likely</em> to cause trouble can help reduce the probability that they <em>will</em> cause trouble.  While there is no substitute for experience and knowledge, good unit testing can help catch many of these before they get buried under layers of other code!</p>
<p>Related articles:</p>
<ul>
<li><a href="http://www.learncpp.com/general-programming/six-language-independent-ways-to-write-better-code/">Six language-independent ways to write better code</a></li>
</ul>
<p><p><hr>
Have a <a href="http://csrc.nist.gov/">computer</a> and looking to obtain a c++ education through an <a href="http://www.onlinedegreereviews.org/">online degree</a> learning program? Get your degree in <a href="http://www.onlinedegreereviews.org/college/cat/computers-and-technology/programming/">computer programming</a> or any degree that will advance your <a href="http://saturn.jpl.nasa.gov/education/edu-k4.cfm">education</a> for the future.
<br><hr></p> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/feed/</wfw:commentRss>
		<slash:comments>5</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('id511679080'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id511679080" 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('id1213854105'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id1213854105" 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('id905884243'), this, 'Show Solution', 'Hide Solution')">Show Solution</a></p>
<div class="solution_div" id="id905884243" 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>6 ways to write better code</title>
		<link>http://www.learncpp.com/cpp-programming/6-ways-to-write-better-code/</link>
		<comments>http://www.learncpp.com/cpp-programming/6-ways-to-write-better-code/#comments</comments>
		<pubDate>Sat, 02 Jun 2007 07:15:48 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++ Programming]]></category>

		<guid isPermaLink="false">http://www.learncpp.com/?p=29</guid>
		<description><![CDATA[There was an article linked from Digg posted up a couple days ago entitled &#8220;6 ways to write better code&#8221;.   It&#8217;s pretty good advice (for the most part), so I thought I&#8217;d link it here.
http://www.ibm.com/developerworks/linux/library/l-clear-code/index.html?ca=drs-
Here are the recommendations of the author, along with my own comments:
1) Comment like a smart person.
I can&#8217;t emphasize [...]]]></description>
			<content:encoded><![CDATA[<p>There was an article linked from Digg posted up a couple days ago entitled &#8220;6 ways to write better code&#8221;.   It&#8217;s pretty good advice (for the most part), so I thought I&#8217;d link it here.</p>
<p><a href="http://www.ibm.com/developerworks/linux/library/l-clear-code/index.html?ca=drs-">http://www.ibm.com/developerworks/linux/library/l-clear-code/index.html?ca=drs-</a></p>
<p>Here are the recommendations of the author, along with my own comments:<br />
<em>1) Comment like a smart person.</em></p>
<p>I can&#8217;t emphasize this enough.  Code that seems beyond obvious has a funny way of reading like a foreign language after a couple of months.  Comment everything &#8212; and don&#8217;t just state the obvious.  Try to write the comment as if you were writing it for someone else who has no prior knowledge of what you are doing.  Because in three or six months, that person will be you.</p>
<p><em>2) Use #define a lot. No, a LOT.</em></p>
<p>Right sentiment, wrong implementation.  As the article says, it&#8217;s a very bad idea to hard-code numbers into your program.  Inevitably, you&#8217;ll want to change something in the future, and it&#8217;s really difficult if everything there are numbers scattered everywhere.  Using #define helps document what you are doing, and makes it easy to change those numbers in the future.</p>
<p>But #define is so&#8230; C.  There are a few problems with using #defines.  First, because #define is a preprocessor command, the preprocessor goes through and replaces all your defined names with their corresponding values.  This means those names are not available when you are debugging, which makes debugging more difficult.  Assume you have a function call that passes in a #defined value called EXP_PER_KILL.  Even though the code you are debugging may says AddExp(EXP_PER_KILL), you won&#8217;t have any idea what EXP_PER_KILL evaluates to unless you can locate it&#8217;s definition.  </p>
<p>Second, #defined variables are always declared in the global scope regardless of where they are defined.</p>
<p>In the world of C++, we can do better.  One better choice is to use a const variable.  Const variables are actual objects, so you can easily get their values in the debugger, and they follow normal scoping rules.  The other better choice is to use an enum, which has the same benefits.</p>
<p><em>3) Don&#8217;t use variable names that will mock you.</em></p>
<p>Not much to say about this &#8212; naming your variables things that makes their purpose clear is an important aspect of documenting your code.</p>
<p><em>4) Do error checking. You make errors. Yes, you.</em></p>
<p>This one is both easier and harder than it looks.  Inevitably you will misuse a function you wrote by passing it an invalid parameter, or something will go wrong and a pointer will end up NULL when you were expecting it to have a value or vice-versa.  Checking for these things is good and can and will keep your program from crashing.  However, if you do detect an error and then do not do anything intelligent with that information, your program might as well just crash and get it over with.</p>
<p>Just as big a problem as detecting an error is doing something intelligent about it.  If you&#8217;re writing a reusable function, the intelligent thing generally involves informing your caller that something went wrong and leaving it up to the caller to handle the problem.  If you&#8217;re the caller, or you&#8217;re writing a function that&#8217;s integral to your program, figuring out how to handle errors can be a tricky proposition.  Do you pop up a message box warning?  Do you ask the user for new input?  Do you save the user&#8217;s data and then terminate the program?  It really depends, and there&#8217;s no easy solution.</p>
<p>But before you can do any of these things, you have to detect than an error occurred, and that&#8217;s why I agree with the author that this is important.</p>
<p><em>5) &#8220;Premature optimization is the root of all evil.&#8221; &#8211; Donald Knuth</em></p>
<p>One of the biggest problems new or overzealous programmers run into is trying to write code that is as fast as possible at the expense of things like code readability.  This is almost always a bad idea.  It IS a good idea to pick an algorithm that&#8217;s right for the problem you&#8217;re trying to solve &#8212; for example, if you&#8217;re doing lots of element insertions and deletions, a linked list is probably going to be a better choice than an array.  But that doesn&#8217;t mean you have to design an algorithm that squeezes out every last bit of performance out of the linked list.  Efficiency generally comes at the expense of legibility, and honestly, with a few exceptions, legibility is more important, because at some point, you&#8217;re going to have to fix a bug, or expand your code, and code that&#8217;s tricked-out to be as efficient as possible isn&#8217;t going to be conducive to either of those things.</p>
<p>Once your code is written, you can always profile it to find out where the ACTUAL bottlenecks are, rather than prematurely act on where you perceive the bottlenecks may be.  With properly implemented code that utilizes concepts such as encapsulation, swapping out one algorithm for a better one when needed is often no problem.</p>
<p><em>6) Don&#8217;t be too clever by half.</em></p>
<p>This is sort of along the same lines as #5.  It&#8217;s almost always a better idea to write code that is clean, straightforward, and legible than code that is as efficient as possible.  As I wrote in the section on comments, if you need a comment to explain <em>what</em> your line of code is doing, it probably needs to be rewritten, not commented.</p>
<p>Many of you have heard of the KISS acronym &#8212; Keep It Simple, Stupid.  It applies to code too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.learncpp.com/cpp-programming/6-ways-to-write-better-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
