    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Programmersâ€™ Puzzles</title>
        <link>https://members.accu.org/index.php/articles/2456</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Design of applications and programs + CVu Journal Vol 29, #6 - January 2018</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c67/">Design</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c381/">296</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c67-381/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c67+381/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Programmersâ€™ Puzzles</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 04 January 2018 16:57:31 +00:00 or Thu, 04 January 2018 16:57:31 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Francis Glassborow reviews his last challenge and presents a new one.</p>
<p><strong>Body:</strong>&nbsp;<p>As any magazine editor (commercial or otherwise) knows, the number of responses to a competition is a small fraction of those who tried it. Readers often try competitions and even finish them but choose not to send in their solutions. I know how many of the <em>New Scientist</em>â€™s puzzles I solved â€“ about 50% in the days when they ran a regular one â€“ yet I never sent in one of my solutions. I also regularly tackle the Bridge competitions in the <em>English Bridge Union</em> magazine but never submit an answer. That behaviour makes me depressingly normal.</p>

<p>My first challenge required you to find some difference between C and C++ that could be exploited to switch the behaviour of a program. The difference could manifest at any stage from pre-processor through to run time behaviour.</p>

<p>I had in mind many little differences that might be exploited. In a way the more interesting ones are those that can trap programmers writing real code. A couple of quick examples:</p>

<p>The way in which the struct keyword introduces a name. C, for reasons that will seem strange to modern programmers, has a completely separate namespace (do not confuse with the C++ keyword <code>namespace</code>) for typenames created by the keywords struct and union. That is the reason that portable code (code that will necessarily behave the same way both as C and C++) couples a <code>typedef</code> with <code>struct</code> in the idiom:</p>

<pre class="programlisting">
  typedef struct A {
    // declarations
  } A;</pre>
  
<p>A C compiler distinguishes between the plain name <code>A</code> and the elaborated name <code>struct A</code>.</p>

<p>Here is an example from James Holland.</p>

<p class="blockquote">If I understand Francisâ€™s challenge correctly, what is needed is some source code that will produce two different outputs depending on whether the code was compiled by a C compiler or a C++ compiler. I assume using built-in compiler macros is not allowed! The solution must, therefore, rely on the code behaving differently depending on which compiler is used. My solution makes use of the fact that a C++ compiler enters the name of a struct in the scope in which it is declared. A C compiler does not do this. The following code [in Listing 1] makes use of this feature.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include&lt;stdio.h&gt;
typedef char T;
int main()
{
  struct T {char c[2];};
  printf(&quot;I was compiled by a C&quot;);
  if (sizeof(T) == 2)
    printf(&quot;++&quot;);
  printf(&quot; compiler.\n&quot;);
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p class="blockquote">When evaluating <code>sizeof(T)</code>, a C compiler will not see <code>T</code> as being the name of the <code>struct</code> as it is not within scope but will see the global <code>typedef</code> and conclude that <code>sizeof(T)</code> is 1. The body of the <code>if</code> statement will, therefore, not be executed. A C++ compiler, on the other hand, will see the locally declared <code>struct</code> and conclude that <code>sizeof(T)</code> is 2. The <code>if</code> statement can then be used to realise the different behaviour as required.</p>

<p>I will deal with Jamesâ€™ assumption about the allowability of built-in compiler macros later. However, there is a flaw in Jamesâ€™ code that means that it will often fail to work as expected because compilers are not prohibited from adding padding at the end of a <code>struct</code> so his test for equality with 2 will often fail because the compiler (usually for alignment purposes) may have added space at the end of <code>T</code>. Existing compilers will frequently return 4 or 8 for the <code>sizeof</code> <code>T</code> (the <code>struct</code> version).</p>

<pre class="programlisting">
  if( sizeof (T) == 2)</pre>
  
<p>needs to be replaced by</p>

<pre class="programlisting">
  if (sizeof(T) &gt; 1;</pre>
  
<p>Apart from the flaw, the idea will work for any type, not just <code>char</code>.</p>

<p>Note that James avoided the flawed use of:</p>

<pre class="programlisting">
  sizeof (char) == sizeof â€˜aâ€™;</pre>
  
<p>as a test. This will usually work because character literals are of type <code>int</code> in C and <code>char</code> in C++. However, some compilers (largely for DSPs) use the same storage allocation for <code>int</code> and <code>char</code> types.</p>

<p>The other aspect is that James assumed that built-in compiler macros were not allowed. In these challenges, anything not explicitly excluded is allowed. Every C++ compiler is supposed to have <code>__cplusplus</code> as a built-in macro. This is absolutely essential so that code can test which version of C++ is in use. I leave it to the reader to surf the net to discover what values are required for conforming C++ compilers. Non-conforming C++ compilers will normally provide a value for <code>__cplusplus</code> but one that is not one of the standard values.</p>

<p>Hubert Matthews exploited this in the first of offering in his submission:</p>

<p class="blockquote">Francis threw out a challenge for pieces of code that produce different results when compiled as C or as C++.Â  Here are two: one cheaty [Listing 2] and one sneaky [Listing 3].</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// prints &quot;C&quot; when compiled as C and &quot;C++&quot; 
// when compiled as C++

include &lt;stdio.h&gt;
int main()
{
   puts(&quot;C&quot;
#ifdef __cplusplus
   &quot;++&quot;
#endif
 );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// prints &quot;12&quot; when compiled as C 
// and &quot;13&quot; when compiled as C++

#include &lt;stdio.h&gt;
int main()
{
  auto x = 5.6, y = 7.5;
  printf(&quot;%d\n&quot;, (int) (x+y));
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>I do not think that is a cheat. It shows a grasp of what is provided by the C++ Standard but I think he did not fully exploit the potential of the pre-processor to bizarrely alter the behaviour of code.</p>

<p>Using <code>__cplusplus</code> gives us all kinds of potential. Instead of conditionally adding a couple of characters at compile time, we can define complicated macros. We even have the ability to redefine a C++ keyword that is not also a C keyword for when our code is being compiled as C, without stepping into undefined territory. For example something such as:</p>

<pre class="programlisting">
  #ifndef __cplusplus
  #define try struct A
  #endif</pre>

<p>will work if we can design code that is a <code>try</code> block in C++ but a <code>struct</code> definition in C. That is just an idea for the reader to think about (replacing keywords, not specifically replacing <code>try</code>).</p>

<p>Hubertâ€™s second offering is interesting.</p>

<p>I have not been able to check that <code>auto x</code> without an explicit <code>int</code> specifier is allowed in current versions of C (post the abolition of â€˜implicit <code>int</code>â€™). GCC in C mode gives me a warning that <code>auto x</code> defaults to <code>auto int x</code>, which is sane even if it is not required that strictly conforming C makes the <code>int</code> explicit.</p>

<p>I leave it as an exercise for the reader to work out why this code produces different output. (Hint, you need C++11 or later compiler to reliably see the difference).</p>

<p>My choice of winner of this challenge is Hubert because his use of <code>auto</code> surprised me and highlighted another potential trap for the unwary C programmer accidentally using a C++ compiler. Of course, no reasonable C programmer uses <code>auto</code> and I suspect quite a number do not even know it is a C keyword.</p>

<h2>Challenge 2</h2>

<p>In the early days of computing, a frequent task was to write code with a missing instruction (such tests were even frequently set in Computer Science A level papers of the early 1980s).</p>

<p>I think it is time to revive this kind of mind exercise. As an example to get you on track, suppose that you have no <code>+</code> available, you could write</p>

<pre class="programlisting">
  template &lt;typename T&gt; 
  T add (T a, T b){
    T result = -b);
    return  a â€“result;
  };</pre>
  
<p>which will work for any type that supports minus as an inverse operation to plus. You would then need to specialise for other types such as <code>std::string</code>. That would be an interesting challenge in itself but it is not what I am going to set you.</p>

<p>The challenge is to write code that will assign the sum of two integer values, <code>a</code> and <code>b</code> and store the result in <code>c</code> without using the <code>=</code> symbol in your code. There are several simple solutions. Bonus points for multiple solutions.</p>

<p>You are restricted to C and C++ because those are the languages that I am familiar with (well you could try it in Forth, Prolog or Snobol?)</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
