 
    
<?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>c++ Archives - Complete, Concrete, Concise</title>
	<atom:link href="https://complete-concrete-concise.com/tag/c-3/feed/" rel="self" type="application/rss+xml" />
	<link>https://complete-concrete-concise.com/tag/c-3/</link>
	<description>Practical Information Without The Bloat</description>
	<lastBuildDate>Tue, 19 Mar 2013 08:38:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
	<item>
		<title>Programming Error &#8211; Unintended String Concatenation</title>
		<link>https://complete-concrete-concise.com/programming/c/programming-error-unintended-string-concatenation/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Tue, 19 Mar 2013 08:38:42 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[comma]]></category>
		<category><![CDATA[concatenation]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[programming]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/?p=2699</guid>

					<description><![CDATA[<p>In an effort to be helpful, C and C++ compilers concatenate adjacent strings together. In the following example, the compiler will concatenate the two strings into a single string: printf("This is a string " "and this is another string."); Which is probably what you intended anyway. Because C and C++ are free form languages, adjacent [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c/programming-error-unintended-string-concatenation/">Programming Error &#8211; Unintended String Concatenation</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In an effort to be helpful, C and C++ compilers concatenate adjacent strings together.</p>
<p>In the following example, the compiler will concatenate the two strings into a single string:</p>
<pre><code>printf("This is a string " "and this is another string.");</code></pre>
<p>Which is probably what you intended anyway.</p>
<p>Because C and C++ are free form languages, adjacent strings can appear in many different formats &#8211; as this string table shows:</p>
<pre><code>char *array[] = {
    "str_1",
    "str_2",
    "str_3"
    "str_4",
    "str_5",
    NULL};</code></pre>
<p>Did you notice the missing comma (,) after <code>"str_3"</code>? It can be a hard one to spot.</p>
<p>This is the type of bug that can result in something like a simple parser failing:</p>
<pre><code>if (strcmp(array[i], test_string) == 0)</code></pre>
<p>because <code>str_3</code> and <code>str_4</code> will never be matched, but the others will.</p>

<p>The post <a href="https://complete-concrete-concise.com/programming/c/programming-error-unintended-string-concatenation/">Programming Error &#8211; Unintended String Concatenation</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Keyword &#8211; switch, case, default</title>
		<link>https://complete-concrete-concise.com/programming/c/keyword-switch-case-default/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Thu, 22 Mar 2012 06:56:52 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[break]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[case]]></category>
		<category><![CDATA[default]]></category>
		<category><![CDATA[keyword]]></category>
		<category><![CDATA[switch]]></category>
		<category><![CDATA[understanding]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/?p=1594</guid>

					<description><![CDATA[<p>The switch keyword is probably the least well understood of the C/C++ language keywords (although, const probably comes a close second). The keywords switch, case, and default always go together and cannot be used independently in any other context. There is a small difference in behaviour between C and C++. Most programmers will never notice [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c/keyword-switch-case-default/">Keyword &#8211; switch, case, default</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="c1">
<p>The <code>switch</code> keyword is probably the least well understood of the C/C++ language keywords (although, <code>const</code> probably comes a close second).</p>
<p>The keywords <code>switch</code>, <code>case</code>, and <code>default</code> always go together and cannot be used independently in any other context.</p>
<p>There is a small difference in behaviour between C and C++. Most programmers will never notice the difference.</p>
</div>
<p>The most common use of <code>switch</code> is as a replacement for multiple <code>if-else</code> statements:</p>
<pre><code>
                               switch (value)
                               {
if (value == 1)                   case 1:
{                                      ...
  ...                                 break;
} else if (value == 2)            case 2:
{                                      ...
  ...                                 break;
} else                            default:
{                                      ...
  ...                                 break;
}                              }</code></pre>
<p>This usage is quite well understood. Its use as a jump table into a block of code is less well understood (and, to be honest, rarely used).</p>
<h1>Format</h1>
<pre><code><strong>switch</strong> ( <em>controlling expression</em> )
{
   <strong>case</strong>: <em>constant expression</em>  // optional
         .        .
         <em>code statements</em>
         .        .
         break;  // optional
   <strong>default</strong>:  //optional
         .        .
         <em>code statements</em>
         .        .
         break;  // optional
}</code></pre>
<h3>switch (<em>controlling expression</em>)</h3>
<p>Every <code>switch</code> block must begin with the <code>switch</code> keyword. If you want a <code>switch</code> block then you have to use the <code>switch</code> keyword.</p>
<p>C and C++ differ in the way the <em>controlling expression</em> is handled. </p>
<p><u><strong>In C</strong></u> the expression is converted to type <code>int</code> using C conversion rules. This means the <em>controlling expression</em> can be anything C knows how to convert to an <code>int</code>: the signed and unsigned varieties of <code>char</code>, <code>short</code>, <code>int</code>, <code>long </code> and <code>long long</code> as well as <code>float</code>, <code>double</code>, and <code>long double</code>.</p>
<p><u><strong>In C++</strong></u> the <em>controlling expression</em> must be an <u>integral</u> type &#8211; any of the signed or unsigned varieties of <code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, or <code>long long</code> &#8211; or any <code>class</code>, <code>struct</code>, or <code>union</code> for which there exists an unambiguous conversion to an integral type. Using a <code>float</code>, <code>double</code>, or <code>long double</code> is an error (unless, of course, you explicitly cast it to one of the integral types).</p>
<div class="c1">
<p>An &#8220;implicit&#8221; conversion from a <code>class</code>, <code>struct </code>or <code>union </code>to an integral type might seem new to some. Here is an example:</p>
<pre><code>class A
{
 private:
    int value;
 public:
    operator int() {return value;} // conversion method
};</code></pre>
<p>This can be used in a <code>switch</code> statement as follows:</p>
<pre><code>
int main(void)
{
   A a;  // variable of type A above with conversion to int
   switch (a) // works because compiler calls operator int()
   {
      .
      .
      .
   }
   return 0;
}</code></pre>
<p>In the above example, when an object of type A is used anywhere a type <code>int</code> is expected, the conversion operator <code>int()</code> will be called.</p>
<p>If we expand the class by adding another conversion operator to a different integral type, say</p>
<pre><code>operator char() {return char(value);}</code></pre>
<p>then it is no longer unambiguous because there are two integral types to choose from: <code>int</code> or <code>char</code>. The compile will fail because the compiler cannot resolve between the two integral types.</p>
<p>Conversions can be ambiguous in other types of code as well:</p>
<pre><code>A a;
int i;
char c;
short s;
i = a; // compiler calls operator int()
c = a; // compiler calls operator char();
s = a; // compiler cannot resolve between int() and char()</code></pre>
</div>
<h3>case (<em>constant expression</em>)</h3>
<div class="c1">
<p><code>case</code> statements are optional &#8211; you don&#8217;t have to have any. But, you do need at least one <code>case</code> or <code>default</code> statement in your <code>switch</code> body.</p>
</div>
<p>The <em>constant expression</em> is called a <u>label</u> or <u>case label</u>.</p>
<p>Unlike the <em>controlling expression</em>, the <code>case</code> label must be known at compile time &#8211; it cannot be a variable or in any other way determined at run time.</p>
<p>All <code>case</code> labels must be different. If two <code>case</code> labels resolve to the same value, then the program is malformed and the compile will fail.</p>
<div class="c1">
<p>The two most common ways that <code>case</code> labels get the same value is through macros or enums:</p>
<pre><code>
// at one time, the following macros all had different values
// but at some point the difference between CONDITION_1 and
// CONDITION_2 was lost and they became the same.
// Most code will work just fine with this change, but not a
// switch block if it is using these labels.
#define CONDITION_1 0
#define CONDITION_2 0  // duplicated value
#define CONDITION_3 2
// instead of using macros, the conditions were encapsulated
// in an enum, but at some point the difference between CONDITION_1
// and CONDITION_2 was lost and they became the same.
// Most code will work just fine with this change, but not a
// switch block if it is using these labels.
enum Some_Values
{
   CONDITION_1 = 0,
   CONDITION_2 = 0, // duplicated value
   CONDITION_3 = 1
};
// when either the macros or enum values are used for the case
// labels, the program becomes malformed because two labels
// have the same value
switch (value)
{
   case CONDITION_1:
   case CONDITION_2: // compile will fail
   case CONDITION_3:
   default:
}</code></pre>
</div>
<p>C and C++ differ in the way they handle the <em>constant expression</em>.</p>
<p><u><strong>In C</strong></u>, the the expression is converted to type <code>int</code>. Both the <em>controlling expression</em> and <em>constant expression</em> are of type <code>int</code>.</p>
<p><u><strong>In C++</strong></u>, the expression is converted to the type of the <em>controlling expression</em>. This means the <em>constant expression</em> is the same type as the <em>controlling expression</em>.</p>
<h3>default</h3>
<div class="c1">
<p>The <code>default</code> statement is optional &#8211; you don&#8217;t have to have one. But, you do need at least one <code>case</code> or <code>default</code> statement in your <code>switch</code> body.</p>
</div>
<p>The <code>default</code> statement is where the <code>switch</code> operator jumps to if none of the <code>case</code> labels match the <em>controlling expression</em>.</p>
<h1>Using switch for Multiway Selection</h1>
<div class="c1">
<p>This is the most common (and best understood) use of the <code>switch</code> statement.</div>
<p>The <code>switch</code> statement is most commonly used when you want to choose one of several code paths and the decision is based on some sort of integer value (an <code>enum</code> is an integer at heart).</p>
<p>For simple choices, an <code>if-else</code> block works fine. But when you have many possible code paths to choose from, having a long chain of <code>if-else</code> statements can be unwieldy.</p>
<p>Consider a basic DVD player that responds to the following commands:</p>
<pre><code>enum PLAYER_COMMANDS
{
   Off,
   On,
   Stop,
   Play,
   Pause,
   Eject
};</code></pre>
<p>Implemented using <code>if-else</code> statements, the code would look like this:</p>
<pre><code>if (command == Off)
{
   ... code ...
}
else if (command == On)
{
   ... code ...
}
... remaining else-if code ...
else
{
   printf("Error - unknown state\n");
}</code></pre>
<p>Using a <code>switch</code> statement, the code would look like this:</p>
<pre><code>switch (command)
{
   case Off:
      ... code ...;
      break;
   case On:
      ... code ...;
      break;
   ... remaining cases ...
   default:
      printf("Error - unknown state\n");
}</code></pre>
<p>The <code>switch</code> block looks neater and more compact than the nested <code>if-else</code> code.</p>
<h3>Order of case statements</h3>
<p>The <code>case</code> and <code>default</code> statements inside the <code>switch</code> don&#8217;t have to be in any particular order. While not typical, it is perfectly valid to have the <code>default</code> statement at the top of the block (or in the middle of the block):</p>
<pre><code>switch (controlling_expression)
{
   default: <em>// not typical location, but perfectly legal</em>
      ... some code ...
      break;
   case label_1:
      ... some code ...
     break;
};</code></pre>
<h3>Use of break</h3>
<p>Usually, a <code>break</code> statement is placed at just before the next <code>case</code> (or <code>default</code>) statement.</p>
<p>Code execution stops at the <code>break</code> statement and continues at the next statement following the <code>switch</code> block.</p>
<p>If there is no <code>break</code> statement, then the code continues to be executed until either (1) a <code>break</code> statement is encountered, or (2) execution exits the <code>switch</code> block.</p>
<pre><code>switch (controlling_expression)
{
   case label_1:
      ... some code 1 ...
   case label_2:
      ... some code 2 ...
      break;
   default:
      ... some code 3 ...
};</code></pre>
<p>In the above example, if the <em>controlling_expression</em> switches to:</p>
<ul>
<li><u>label_1</u>: then <em>some code 1</em> will be executed. Since there is no <code>break</code> statement, execution will fall through and execute <em>some code 2</em>. Since there is a <code>break</code> after <em>some code 2</em> code execution will continue at the next statement following the <code>switch</code> block.</li>
<li><u>label_2</u>: then <em>some code 2</em> will be executed. Since there is a <code>break</code> statement, code execution will continue at the next statement following the <code>switch</code> block.</li>
<li><u>default</u>: then <em>some code 3</em> will be executed. There is no <code>break</code> statement (it is optional for the last final label) because the next statement to be executed will be the one following the <code>switch</code> block.</li>
</ul>
<h3>Using Fall-through</h3>
<p>Fall-through can be useful.</p>
<p>Unlike some other languages, C and C++ don&#8217;t allow a range of values for for a <code>case</code> label. For example, you could not write:</p>
<pre><code>switch (month)
{
   case January ... July :
      ... some code ...
};</code></pre>
<p>But, using fall-through, you can write code like this:</p>
<pre><code>switch (month)
{
   case January:
   case March:
   case May:
   case July:
   case August:
   case October:
   case December:
      days = 31;
      break;
   case April:
   case June:
   case September:
   case November:
     days = 30;
     break;
   case February:
     days = 28;
};</code></pre>
<p>In the above example, January falls through to the assignment <code>days = 31;</code></p>
<h1>Using switch as a Jump Table</h1>
<div class="c1">
<p>This is the least commonly understood and used behaviour of the <code>switch</code> statement. Its most infamous example is <u>Duff&#8217;s Device</u>.</p>
</div>
<p>A common complaint of programmers coming from other languages is that the <code>switch</code> in C and C++ is broken &#8211; it seems dumb to have to explicitly code a <code>break</code> to prevent fall-through in <code>case</code> statements. That&#8217;s because in most languages a <code>switch</code> or <code>case</code> block is compact way of selecting a block of code to execute. This is not the case in C and C++. In C and C++, the <code>switch</code> statement is not for selecting a block of code to execute, it is a <u>jump table</u> <u>into</u> a block of code.</p>
<p>Consider the following:</p>
<pre><code>switch (control)
{
   default:
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
}</code></pre>
<p>No matter what value <code>control</code> has, the 8 <code>printf</code> statements will be executed. We might as well not even have the <code>switch</code> statement to begin with. The code is, effectively, identical to 8 <code>printf</code> statements enclosed in their own block:</p>
<pre><code>{
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
   printf ("Hello world!!!\n");
}</code></pre>
<p>We could also write it this way:</p>
<pre><code>goto DEFAULT: // whatever the value of control
{
DEFAULT:
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
}</code></pre>
<p>Consider the following (which will print Hello World!!! either 1, 2, 3, 4, 5, or 8 times depending on the value of <code>control</code>):</p>
<pre><code>switch (control)
{
   default:
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
   case 5:
      printf ("Hello world!!!\n");
   case 4:
      printf ("Hello world!!!\n");
   case 3:
      printf ("Hello world!!!\n");
   case 2:
      printf ("Hello world!!!\n");
   case 1:
      printf ("Hello world!!!\n");
}</code></pre>
<p>It can be rewritten as:</p>
<pre><code>if (control == 1) goto LABEL_1;
if (control == 2) goto LABEL_2;
if (control == 3) goto LABEL_3;
if (control == 4) goto LABEL_4;
if (control == 5) goto LABEL_5;
else goto DEFAULT;
{
DEFAULT:
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
      printf ("Hello world!!!\n");
LABEL_5:
      printf ("Hello world!!!\n");
LABEL_4:
      printf ("Hello world!!!\n");
LABEL_3:
      printf ("Hello world!!!\n");
LABEL_2:
      printf ("Hello world!!!\n");
LABEL_1:
      printf ("Hello world!!!\n");
}</code></pre>
<p>It should be obvious that a <code>switch</code> block is a constrained <code>goto</code> where you can jump to any line inside the block via an appropriate <code>case</code> label.</p>
<div class="c1">
<p>There is no need to get alarmed, <u>every</u> control statement in <u>every</u> programming language that alters the flow of program execution is a constrained goto.</p>
<p>Consider a <code>do-while</code> loop:</p>
<pre><code>do
{
   x = x + 2;
}
while (x &lt; 100);</code></pre>
<p>This is identical to:</p>
<pre><code>DO:
{
   x = x + 2;
}
if (x &lt; 100) goto DO;</code></pre>
</div>
<p>Knowing this helps to understand some of the &#8220;weird&#8221; behaviour of the <code>switch</code> statement in C and C++.</p>
<h3>Fall-through</h3>
<p>Fall through occurs because we <u>do not select</u> a block of code to execute, but <u>jump to a line of code</u> (within the block) and continue execution from there.</p>
<p>The <code>break</code> at the end of what we want to execute is simply a <code>goto</code> to the end of the block.</p>
<div class="c1">
<p>Looked at another way, <code>switch</code> or <code>case</code> constructs in other languages do exactly the same thing, except that before the next label, they implicitly insert a <code>goto</code> to the end of the block.</p>
<p>Consider the following example in Pascal:</p>
<pre><code> case A of
   0: writeln('nothing');
   1: writeln('number 1');
   2: writeln('number 2');
   else writeln('big number');
 end;</code></pre>
<p>This is identical to:</p>
<pre><code>if A = 0 then goto ZERO;
if A = 1 then goto ONE;
if A = 2 then goto TWO else goto BIG;
ZERO:
   writeln('nothing');
   goto CONTINUE;
ONE:
   1: writeln('number 1');
   goto CONTINUE;
TWO:
   2: writeln('number 2');
   goto CONTINUE;
BIG:
   writeln('big number');
CONTINUE:</code></pre>
<p>Notice the implicit <code>goto</code>s inserted to prevent fall-through.
</div>
<h3>Initialization Errors</h3>
<p>It is common to want to use some local variables in a <code>case</code> label. Unfortunately, doing so can generate a compile time error that the variable has not been initialized:</p>
<pre><code>switch (value)
{
   int a = 7;
   case 1:
       printf("%d\n", a);
       break;
   default:
       printf("%d\n", a * a);
}</code></pre>
<p>In this example, when the code jumps to <code>case 1</code> or <code>default</code> it bypasses the initialization of <code>a</code>.</p>
<h3>Jumping into the middle of and embedded switch</h3>
<p>Since a <code>switch</code> statement allows you to jump to an arbitrary point in a block of code, it is reasonable to ask if it is possible to jump into the middle of a nested <code>switch</code> block:</p>
<pre><code>switch (value)
{
   case LABEL_1:
      switch (value_2)
      {
         case OTHER_LABEL_1:
            ... code ...
            break;
         case LABEL_2:  // can <strong>switch (value)</strong> jump here?
            ... code ...
            break;
      }
   case LABEL_3:
      ... code ...
      break;
}</code></pre>
<p>The answer is <strong>no</strong>. This is because scope and visibility rules don&#8217;t allow <code>value</code> of the first <code>switch</code> to be seen inside of the nested <code>switch</code> block.</p>
<p>The following should make this clear:</p>
<pre><code>int A = 7; // this is the outer_A
{   // start a new block
   int A = 3; // this is the inner_A
  // inside this block, the value of the outer_A is not visible
  // (ok, in C++ you could use the :: scope resolution operator
  //  to see the outer_A, but that is not the point)
}</code></pre>
<p>In a similar way, the value of the <em>controlling expression</em> in the outer <code>switch</code> is hidden by the value of the <em>controlling expression</em> of the nested <code>switch</code>. This means the outer <em>controlling expression</em> has no scope within the nested <code>switch</code>, so it cannot jump into the middle of a nested <code>switch</code>.</p>

<p>The post <a href="https://complete-concrete-concise.com/programming/c/keyword-switch-case-default/">Keyword &#8211; switch, case, default</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Debugging &#8211; An Easy Way to Catch Typing Errors in C++</title>
		<link>https://complete-concrete-concise.com/programming/c-programming/debugging-an-easy-way-to-catch-typing-errors-in-c/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Fri, 10 Jun 2011 03:44:49 +0000</pubDate>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[strong types]]></category>
		<category><![CDATA[type errors]]></category>
		<category><![CDATA[type mismatch]]></category>
		<category><![CDATA[types]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/programming/c-programming/debugging-an-easy-way-to-catch-typing-errors-in-c</guid>

					<description><![CDATA[<p>A common bug in C++ programming is mixing different data types together &#8211; generally, this is inadvertent. I developed this technique back in 1997 or 1998 after my recommendation that all types be made classes was shot down. It requires your programming style does not use the fundamental C++ data types directly, but instead you [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c-programming/debugging-an-easy-way-to-catch-typing-errors-in-c/">Debugging &#8211; An Easy Way to Catch Typing Errors in C++</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="c1">
<p>A common bug in C++ programming is mixing different data types together &#8211; generally, this is inadvertent. </p>
<p>I developed this technique back in 1997 or 1998 after my recommendation that all types be made classes was shot down.</p>
<p>It requires your programming style does not use the fundamental C++ data types directly, but instead you rename them using a <code>typedef</code>.</p>
</div>
<p>You follow good programming practice and don&#8217;t use fundamental C++ types directly, but hide them behind a <code>typedef</code>. Unfortunately, <code>typedef</code> only gives it a new name, but does not create a new type.</p>
<div class="c2"><code>typedef float TEMPERATURE_C;<br />
typedef float TEMPERATURE_F;<br />
typedef float WIND_SPEED_MPH;<br />
typedef float WIND_SPEED_KMH;<br />
typedef float BAROMETRIC_PRESSURE_KPA;<br />
typedef float BAROMETRIC_PRESSURE_MILLIBARS;</code></div>
<p>While it makes for code that is more self documenting:</p>
<pre>TEMPERATURE_C GetCurrentTemperature(void)
{
    return g_current_temperature;
}</pre>
<p>it does not change the fact that all the new types are really <code>float</code> and that is how the compiler sees them. Because the compiler sees them all as <code>float</code>, you could not create this function returning a &#8220;different&#8221; type:</p>
<pre>TEMPERATURE_F GetCurrentTemperature(void)
{
    Return g_current_temperature * 9 / 5 + 32;
}</pre>
<p>because the compiler will complain that function <code>GetCurrentTemperature</code> has already been defined.</p>
<p>You can also mix and match those newly defined types without complaint from the compiler because they are all <code>float</code>.</p>
<div class="c2"><code>TEMPERATURE_C c = 25.3;<br />
TEMPERATURE_F f = 78.2;<br />
WIND_SPEED_MPH s;<br />
s = c + f;</code></div>
<p>While this example is an &#8220;obvious&#8221; wrong use and abuse of the declared types, this kind of mixing can still happen.</p>
<p>If you are developing software for a weather monitoring application, you likely have types for temperature (both &deg;F and &deg;C) wind speed (both MPH and km/h &#8211; maybe even feet per second and meters per second), barometric pressure (in a variety of units) and others.</p>
<p>To  calculate the average temperature over a period of time, it would be wrong to average both &deg;F and &deg;C temperatures together. Perhaps there is a bug in the code that inadvertently adds a  &deg;C value into the average calculation for &deg;F &#8211; maybe the function <code>GetCurrentTemp()</code> returns the value in &deg;C. It is unlikely to cause a serious discrepancy &#8211; something you can put down to rounding errors or inherent floating point inaccuracy (maybe blame Intel for a floating point bug in their chip).</p>
<p>The compiler certainly won&#8217;t warn you about mixing types. </p>
<p>This is the sort of bug that most programmers would say can only be caught by careful code inspection. But they would be wrong because the compiler can catch these errors for you.</p>
<h1>Let the Compiler Catch Type Mismatches for You</h1>
<p>If we replace the fundamental C++ type with a non-fundamental type, a type that C++ knows nothing about, for which it does not define any implicit conversions for you, then the compiler can catch type mismatch errors for you.</p>
<p>The following class meets most needs for a quick and dirty type replacement &#8211; it defines the basic arithmetic operations and comparisons that are possible on fundamental types (you could extend it to include the bitwise operators and <code>%</code> operator):</p>
<pre>class  dummy
{
public:
    dummy operator+ (const dummy s) {return *this;};
    dummy operator- (const dummy s) {return *this;};
    dummy operator* (const dummy s) {return *this;};
    dummy operator/ (const dummy s) {return *this;};
    dummy operator+= (const dummy s) {return *this;};
    dummy operator-= (const dummy s) {return *this;};
    dummy operator*= (const dummy s) {return *this;};
    dummy operator/= (const dummy s) {return *this;};
    bool operator< (const dummy s) {return false;};
    bool operator> (const dummy s) {return false;};
    bool operator<= (const dummy s) {return false;};
    bool operator>= (const dummy s) {return false;};
    bool operator== (const dummy s) {return false;};
    bool operator!= (const dummy s) {return false;};
};</pre>
<div class="c1">
<p>Note: This class is non-functional, its sole purpose is to help in finding typing errors at compile time. Once all errors are found and corrected, you would restore the original <code>typedef</code></p>
</div>
<p>Because we were good programmers and used <code>typedef</code> to rename the fundamental C++ types, we simply replace an existing <code>typedef</code> with our new type:</p>
<div class="c2"><code>// typedef float TEMPERATURE_C;<br />
typedef dummy TEMPERATURE_C;</code></div>
<p>and then compile our code.</p>
<h1>Why Your Compile Will Fail</h1>
<p>It is unlikely your code will successfully compile. There are 5 reasons for this:</p>
<p>1) this class is incomplete: harmless variable initializations will fail because the class doesn&#8217;t know how to handle them:</p>
<div class="c2"><code>TEMPERATURE_C temp = 37.6; </code></div>
<p>2) you are calling library functions that don&#8217;t know how to use this new type</p>
<div class="c2"><code>TEMPERATURE_C temp;<br />
scanf("Enter a temperature in Celsius %f\n", &temp);</code></div>
<p>3) you are using it in a <code>switch</code> statement:</p>
<pre>// typedef int AGE;
typdef dummy AGE;
.
.
.
AGE age;
.
.
.
    switch (age)
{
        case 1:
        .
        .
        .
}</pre>
<p>4) this class is incomplete: legitimate arithmetic operations will fail (like conversions, scaling, averaging, etc):</p>
<div class="c2"><code>TEMPERATURE_C temp_c;<br />
TEMPERATURE_F temp_f;<br />
.<br />
.<br />
.<br />
temp_f = temp_c * 9 / 5 + 32;</code></div>
<div class="c3">
<p><strong>5) because you have mismatched types in: assignments, operation, or function calls:</strong></p>
<div class="c2"><code>TEMPERATURE_C temp_c;<br />
TEMPERATURE_F temp_f;<br />
TEMPERATURE_F Celsius_To_Fahrenheit(TEMPERATURE_C c);<br />
.<br />
.<br />
.<br />
<strong>// meaningless assignment, should be a conversion</strong><br />
temp_f = temp_c;<br />
.<br />
.<br />
.<br />
<strong>// incorrect type in call to function,<br />
// incorrect assignment of result</strong><br />
temp_c = Celsius_To_Fahrenheit(temp_f);<br />
.<br />
.<br />
.<br />
<strong>// meaningless addition</strong><br />
temp_f = temp_f + temp_c;</code>
</div>
</div>
<h1>Review Each Error</h1>
<p>It&#8217;s not fun, but you have to review each error and decide whether it is a valid one or a spurious one.</p>
<p>However, it beats looking through <strong><u>all </u></strong>the code to try and find <strong><u>all </u></strong>uses of the type. At least the compiler is letting you know where that type is being used and possibly misused (places where the type is unambiguously being used correctly will not appear as errors or warnings).</p>

<p>The post <a href="https://complete-concrete-concise.com/programming/c-programming/debugging-an-easy-way-to-catch-typing-errors-in-c/">Debugging &#8211; An Easy Way to Catch Typing Errors in C++</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Compilation Error &#8211; Improperly Defined Macro</title>
		<link>https://complete-concrete-concise.com/programming/c/compilation-error-improperly-defined-macro/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Wed, 08 Jun 2011 04:57:19 +0000</pubDate>
				<category><![CDATA[C]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[compile error]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[macro]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/programming/c/compilation-error-improperly-defined-macro</guid>

					<description><![CDATA[<p>Macros are tricky things to use in C/C++ programming. When they work, they work great. When they have bugs, they are a pain to troubleshoot. Macros are a simple text substitution done by the preprocessor. Whenever the macro name is encountered in your code, the preprocessor replaces it with the text to the right of [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c/compilation-error-improperly-defined-macro/">Compilation Error &#8211; Improperly Defined Macro</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Macros are tricky things to use in C/C++ programming. When they work, they work great. When they have bugs, they are a pain to troubleshoot.</p>
<p>Macros are a simple text substitution done by the preprocessor. Whenever the macro name is encountered in your code, the preprocessor replaces it with the text to the right of the macro name (plugging in any optional parameters you may have passed).</p>
<p>A macro is composed of three parts:</p>
<ol>
<li><strong>#define</strong> &#8211; this introduces the macro</li>
<li><strong>macro name</strong> and optional parameter list. The macro name cannot have any spaces and the parameter list cannot be separated from the macro name with any spaces.</li>
<li><strong>text that will replace the macro</strong> &#8211; everything following the macro name (and optional parameter list), until the end of the line, is what the preprocessor will use to replace the macro name. For long macros, or for better formatting, the macro can be defined over several lines by ending each line with a backslash character  (\) and a new line (enter) (extra spaces between the backslash character and new line means the macro ends there &#8211; so be careful of extra spaces following the backslash).</li>
</ol>
<h1>Working Examples:</h1>
<p><code></p>
<pre>#define my_macro // preprocessor will replace my_macro with this comment.</pre>
<p></code><br />
<code></p>
<pre>#define my_macro // when the preprocessor encounters my_macro, \
                    it will replace it with everything on this \
                    line that is to the right of the definition \
                    (which is this comment). Fortunately, \
                    it is possible to spread the line over several \
                    lines by using the backslash character</pre>
<p></code></p>
<h1>Not Working Examples:</h1>
<p>The following macro won&#8217;t compile following expansion (it is supposed to replace the macro with the contents of the parameter list):</p>
<div class="c2"><code>#define my_macro (x) x</code><br />
<code>my_macro(int a);</code></div>
<p>The (unhelpful but correct) error message from the compiler (GCC v.4.4.1) is:</p>
<div class="c4"><code>error: expected '=', ',', ';', 'asm' or '__attribute__' before 'x'</code></div>
<p>The problem is the space between the macro name and the parameter list &#8211; there should be none.</p>
<p>Here&#8217;s another macro that won&#8217;t compile (like the one above, it is supposed to replace the macro with the parameters passed) :</p>
<div class="c2"><code>#define my_macro (x, y) x y</code><br />
<code>my_macro(int, abc);</code></div>
<p>The (unhelpful but correct) from the compiler (GCC v.4.4.1) is:</p>
<div class="c4"><code>error: expected ')' before ',' token</code></div>
<p>Again, the problem is a space between the macro name and the parameter list. Removing the space fixes the problem.</p>
<div class="c1">
<p>It is an <strong>error</strong> to separate the macro name and the macro parameter list with a space.</p>
</div>

<p>The post <a href="https://complete-concrete-concise.com/programming/c/compilation-error-improperly-defined-macro/">Compilation Error &#8211; Improperly Defined Macro</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Programming Error &#8211; Incorrect Array Declaration</title>
		<link>https://complete-concrete-concise.com/programming/c-programming/programming-error-incorrect-array-declaration/</link>
		
		<dc:creator><![CDATA[richardsplanet]]></dc:creator>
		<pubDate>Tue, 07 Jun 2011 19:23:19 +0000</pubDate>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[corrupt]]></category>
		<category><![CDATA[crash]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://complete-concrete-concise.com/programming/c-programming/programming-error-incorrect-array-declaration</guid>

					<description><![CDATA[<p>In C++, we can declare an array by using the new operator: char *p = new char[50]; // dynamically allocate an array of 50 char This is useful in functions when we don&#8217;t know in advance how large the array should be or if we want to allocate the array in the heap instead of [&#8230;]</p>
<p>The post <a href="https://complete-concrete-concise.com/programming/c-programming/programming-error-incorrect-array-declaration/">Programming Error &#8211; Incorrect Array Declaration</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In C++, we can declare an array by using the <code><strong>new</strong></code> operator:</p>
<div class="c2"><code>char *p = new char[50]; // dynamically allocate an array of 50 char</code></div>
<p>This is useful in functions when we don&#8217;t know in advance how large the array should be  or if we want to allocate the array in the heap instead of the stack (the equivalent in C would be to use malloc() or calloc() to allocate the array)</p>
<p>A common programming error (because it looks very similar and is perfectly valid) is to replace the [] with ().</p>
<div class="c2"><code>char *p = new char(50);</code></div>
<p>In this case, we have allocated a single char and initialized its value to 50 &#8211; which is not what was intended.</p>
<p>This leads to those hard to track down bugs of corrupted data and / or random crashes.</p>
<p><strong>NOTE:</strong> when freeing an array created with <code><strong>new</strong></code>, remember to call <strong><code>delete[]</code></strong> instead of <code><strong>delete</strong></code> to avoid memory leaks (and definitely never call <code><strong>free()</strong></code>)</p>

<p>The post <a href="https://complete-concrete-concise.com/programming/c-programming/programming-error-incorrect-array-declaration/">Programming Error &#8211; Incorrect Array Declaration</a> appeared first on <a href="https://complete-concrete-concise.com">Complete, Concrete, Concise</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
