 
    
<?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>default Archives - Complete, Concrete, Concise</title>
	<atom:link href="https://complete-concrete-concise.com/tag/default/feed/" rel="self" type="application/rss+xml" />
	<link>https://complete-concrete-concise.com/tag/default/</link>
	<description>Practical Information Without The Bloat</description>
	<lastBuildDate>Thu, 22 Mar 2012 06:56:52 +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>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>
	</channel>
</rss>
