    <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  :: Code Critique Competition 114</title>
        <link>https://members.accu.org/index.php/articles/2570</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">Student Code Critiques from CVu journal. + CVu Journal Vol 30, #5 - November 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/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</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/c392/">305</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+392/">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;Code Critique Competition 114</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 02 November 2018 17:14:16 +00:00 or Fri, 02 November 2018 17:14:16 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Set and collated by Roger Orr. A book prize is awarded for the best entry.</p>
<p><strong>Body:</strong>&nbsp;
<p class="EditorIntro">Note: if you would rather not have your critique visible online please inform me. (Email addresses are not publicly visible.)</p>

<h2>Last issueâ€™s code</h2>

<p class="blockquote">This is a very short code sample but nonetheless an interesting problem.</p>

<p class="blockquote">The writer is using a variadic template to pass multiple arguments to the <code>least</code> function, which uses <code>std::sort</code> to find the smallest input number. They report the code used to work in 32-bit on a couple of compilers, but itâ€™s not reliable when used in more modern 64-bit projects.</p>

<p class="blockquote">Can you identify the problem(s), and suggest any fixes (or alternative approaches)?</p>

<p>The code is in Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;algorithm&gt;
#include &lt;iostream&gt;

// find the least value in the arguments
template &lt;typename T, typename... Ts&gt;
T least(T first, Ts... rest)
{
  std::sort(&amp;first,
    &amp;first + 1 + sizeof...(rest));
  return first;
}
int main()
{
  std::cout &lt;&lt; &quot;least(1): &quot;
    &lt;&lt; least(1) &lt;&lt; std::endl;
  std::cout &lt;&lt; &quot;least(1,2,3,4): &quot;
    &lt;&lt; least(1,2,3,4) &lt;&lt; std::endl;
  std::cout &lt;&lt; &quot;least(10,9,8,7,6,5,4,3,2,1): &quot;
    &lt;&lt; least(10,9,8,7,6,5,4,3,2,1)
    &lt;&lt; std::endl;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<h2>Critiques</h2>

<h3>Gennaro Prota</h3>

<p>Of course, the problem with the code is that it treats distinct variables (function parameters) as if it were accessing elements of the same array. It simply invokes undefined behaviour.</p>

<p>IMHO, the easiest thing to do is to leverage the <code>min_element()</code> algorithm and use <code>std::initializer_list&lt;&gt;</code>:</p>

<pre class="programlisting">
  #include &lt;algorithm&gt;
  #include &lt;initializer_list&gt;
  #include &lt;iostream&gt;
  
  // find the least value
  template &lt;typename T&gt;
  T least(std::initializer_list&lt;T&gt; list)
  {
    // assume list is not empty; it would be nice
    // to be able to do the following:
    // static_assert(list.size() != 0, &quot;&quot;);
    return *std::min_element(list.begin(),
    list.end());
  }
  int main()
  {
    std::cout &lt;&lt; &quot;least({1}): &quot;
      &lt;&lt; least({1}) &lt;&lt; std::endl;
    std::cout &lt;&lt; &quot;least({1,2,3,4}): &quot;
      &lt;&lt; least({1,2,3,4}) &lt;&lt; std::endl;
    std::cout &lt;&lt; &quot;least({10,9,8,7,6,5,4,3,2,1}): &quot;
      &lt;&lt; least({10,9,8,7,6,5,4,3,2,1})
      &lt;&lt; std::endl;
  }</pre>

<h3>Stewart Becker</h3>

<p>So, first off â€“ kudos for wanting to use an <code>&lt;algorithm&gt;</code> rather than rolling your own. This is good practice. Unfortunately, thatâ€™s about all that can be said in praise of this code. There are three main issues with it:</p>

<ol>
	<li>Implementation-defined behaviour</li>
	<li>Undefined behaviour</li>
	<li>Choice of algorithm</li>
</ol>

<p>The key approach used by the function is using the addresses of function arguments as iterators to a standard algorithm. While pointers can be used as iterators, we do need to make sure they form a valid iterator range.   The assumption seems to be that the function arguments will be contiguous in memory so as to behave like an array, meaning that we can use pointer arithmetic to determine the â€˜endâ€™, and incrementing the address of the first argument will give the addresses the others in order. Indeed, it seems all the major compilers and calling conventions involve pushing arguments onto the stack in reverse order, so this effect is to be expected. However, this is a convention and implementation-defined. Furthermore, if a function is inlined then all bets are off regarding the relative memory locations of the arguments.</p>

<p>What I suspect is happening is that in the 32-bit world, an <code>int</code> is the same width as a stack element so the pointer arithmetic trick worked. However, in the 64-bit world <code>int</code>s are only half as wide, so alignment issues come into play. The pointer increment will move forward only in multiples of 32 bits rather than to the next value which is 64 bits away. Trying to force the pointer arithmetic to work in 64-bit might make the trick work again, but I wouldnâ€™t want to count on it. It would be better if we could program to the standard alone, rather than relying on implementation details.</p>

<p>As written, the function exhibits undefined behaviour when passed different types. As written, the <code>Ts...</code> pack can expand to any list of types. We could, for example, pass in an <code>int,</code> a <code>double</code> and an object type, e.g. <code>std::string</code>. The result would still compile, but at runtime it would perform pointer arithmetic based only on the first type, and dereference that memory location as type <code>T</code>, not the <code>Ts...</code> types. Even if we know the types are of the same size this is still undefined behaviour.  If we are lucky, <code>sizeof(first)</code> will be no greater than the average of <code>sizeof(rest)... </code>. We then â€˜onlyâ€™ have to worry about the issues of pointers being dereferenced as the wrong type, and that some values passed lie beyond the end iterator. Weâ€™re still deep in UB territory, but we should just return a wrong result, at least if weâ€™re working with native types like <code>int</code>. With object type then we could very easily get an object in an invalid state, which will cause very hard to debug problems later on, but thatâ€™s a secondary effect. The worst case scenario is if <code>sizeof(first)</code> is large compared to the other arguments. We would then be asking <code>std::sort</code> to operate on memory locations we donâ€™t actually have the right to use. Given that <code>std::sort</code> is a modifying algorithm this means we are overwriting arbitrary memory â€“ a disaster waiting to happen!</p>

<p>We can make a start on both issues at once by changing the function signature. If we want a contiguous memory layout with all arguments of the same type, we can do so by using a collection type that does just that. This is the definition of an array, so letâ€™s start by using one â€“ in the guise of <code>std::array</code> because we want to be modern. Also, we can guarantee check at compile-time when it is empty, which other collections (in particular the usual first choice <code>std::vector</code>) cannot detect. One thing the old code did not have to worry about was finding the least of an empty collection. Weâ€™ll also use actual begin and end iterators instead of pointers:</p>

<pre class="programlisting">
  template&lt;typename T, size_t N&gt;
  T least(std::array&lt;T, N&gt; array)
  {
    static_assert(N &gt; 0, &quot;Empty array&quot;);
    std::sort(array.begin(), array.end());
    return *(array.begin());
  }</pre>
  
<p>Oh dear! Now our calls donâ€™t compile. This is because they are passing many arguments as integers, instead of one array. Weâ€™ll need to modify them to pass as one argument. Instead of <code>least(1,2,3,4)</code> weâ€™ll add curly braces round the arguments and call <code>least({1,2,3,4})</code>.</p>

<p>Nope, that still doesnâ€™t compile. The problem is that <code>{1,2,3,4}</code> isnâ€™t a typed C++ value, therefore the compiler canâ€™t deduce its type. However, there C++ is one type that will accept such syntax: <code>std::initializer_list</code>. But now we need a runtime check for emptiness. Again weâ€™ll be modern and use ADL to lookup the begin and end iterators, just in case we change the type again (hint: we will):</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  T least(std::initializer_list&lt;T&gt; list)
  {
    using std::begin;
    using std::end;
    auto first = begin(list);
    auto last = end(list);
    assert(first != last);
    std::sort(first, last);
    return *first;
  }</pre>
  
<p>WHAT NOW, COMPILER?! We experience the joy of compile errors longer than our codebase that are the signature of programming with templates. It seems that <code>std::sort</code> wonâ€™t work with <code>std::initializer_list</code>. The key error message is <code>error: assignment of read-only location '* __first'</code> (gcc). In English, it means that <code>std::sort</code> is trying to manipulate the values inside the list, but <code>std::initializer_list</code> only provides read-only iterators, even when we passed it by (non-const) value to the least function. Surely it must be possible to get the smallest element from a list without needing to re-order it?</p>

<p>This brings me to the final issue â€“ choice of algorithm. The use of <code>std::sort </code>has two problems. As we have just seen, it is a modifying algorithm, so we cannot use it on ranges that are read-only. Furthermore, it is overkill for finding just the least element as it is takes O(n log n). We really should be able to achieve our goal in a single, read-only pass. Indeed we can, by using the algorithm <code>std::min_element</code>. Since weâ€™re now using a read-only algorithm, weâ€™ll take the list by const reference too:</p>

<pre class="programlisting">
  template&lt;typename T&gt;
  T least(const std::initializer_list&lt;T&gt;&amp; list)
  {
    ...
    return *std::min_element(first, last);
  }</pre>
  
<p>Hooray! It compiles, runs and whatâ€™s more actually works without relying on implementation details. However it only works on containers of type <code>std::initializer_list</code>, which arenâ€™t particularly common. It really would be better if we could pass any container, especially the ubiquitous <code>std::vector</code> and our first attempt, <code>std::array</code>. Also, what it we want to find the greatest element? One of the benefits of <code>std::min_element</code> is that we can pass a customised comparison object, including a lambda. We should template the whole range type:</p>

<pre class="programlisting">
  template&lt;typename Range&gt;
  auto least(Range range)
  /* code unchanged */</pre>
  
<p>Oh no â€“ our examples donâ€™t compile again! The issue is that because brace expressions arenâ€™t actually C++ values, they canâ€™t be type deduced as <code>std::initializer_list</code> objects. Weâ€™ll need to add an overload with the original signature. Since the code in both will be identical. weâ€™ll do this by writing an implementation function and delegating to it in the overloads.</p>

<p>Also, weâ€™ll add a customisable but defaulted comparator:</p>

<pre class="programlisting">
  template&lt;typename Range, typename Comp&gt;
  auto least_impl(Range range, Comp comp)
  {
    /* ... only the last line changes */
    return *std::min_element(first, last, comp);
  }
  template&lt;typename Range,
  typename Comp=std::less&lt;&gt;&gt;
  auto least(Range range, Comp comp={})
  {
    return least_impl(range, comp);
  }
  template&lt;typename T, typename Comp=std::less&lt;&gt;&gt;
  T least(const std::initializer_list&lt;T&gt;&amp; list,
  Comp comp={})
  {
    return least_impl(list, comp);
  }</pre>
  
<p>Hmm, that visible <code>least_impl</code> function is a bit ugly. If this were a class, weâ€™d probably make it private. One trick used is to move it into a separate namespace, often named â€˜detailâ€™ or â€˜implâ€™. But the class approach appeals to me. As for why, when I started this, I forgot about <code>std::min_element</code> and tried to roll my own as <code>std::accumulate(first, last, *first, std::min)</code>, which wouldnâ€™t compile either! The problem is that because <code>std::min</code> is a function overload, the compiler couldnâ€™t work out which one I meant. Our overloads of <code>least</code> mean that trying build algorithm up by passing it as a parameter will suffer the same problem. But if we make it a functor then we can just reference a single unambiguous object. All that changes is how and where we declare the functions, and one final object declaration:</p>

<pre class="programlisting">
  class Least {
  private:    
    template&lt;typename Range,
    typename Comp = std::less&lt;&gt;&gt;
    auto least_impl(Range range, Comp comp) const;
  public:
    template&lt;typename Range,
    typename Comp=std::less&lt;&gt;&gt;
    auto operator()(Range range,
    Comp comp={}) const;
    template&lt;typename T,
    typename Comp=std::less&lt;&gt;&gt;
    T operator()(
    const std::initializer_list&lt;T&gt;&amp; list,
    Comp comp={}) const;
  };
  static constexpr Least least = {};</pre>

<h3>Joe Wood &lt;joew60@yahoo.com&gt;</h3>

<p>By sheer chance I am currently using a 32bit Ubuntu 18.04 distribution. Sometimes it works as expected, sometimes it produces an impossible result, e.g. outside the parameter range, and sometimes it reports a stack smash, so there is obviously something wrong.</p>

<p>Letâ€™s start by trying GCCâ€™s sanitizers, e.g.</p>

<pre class="programlisting">
  g++ -g -O -fsanitize=address \
    -fsanitize=undefined code.cpp</pre>
	
<p>Well, running the compiled code produced some interesting information. (The output is a little too long to reproduce here.) The source of the problem is in the call to <code>std::sort</code>, and the actual bug is in reading and comparing two iterators deep inside <code>std::sort</code>. The offending line is</p>

<pre class="programlisting">
  { return *__it1 &lt; *__it2; }</pre>
  
<p>where <code>__it1</code> and <code>__it2</code> are both iterators.</p>

<p>Why does this fail? We know that sorting an STL conforming container with random access iterators works. Hmm, sorting a valid STL container relies on the data been contiguous <a href="#[W1]">[1]</a>. Is our data contiguous? Unfortunately not; to understand why, we have to turn our attention to how parameters are passed to functions (the calling convention) and the Application Binary Interface (ABI). Firstly, both C and C++ appear to put all parameters on the stack starting at the right hand side and moving leftwards. This is a must for functions like <code>printf</code>, so it knows where to find the format string and hence process all the arguments. Secondly, I said appears to put the arguments on the stack. As an optimisation, a small number of variables may be passed in the CPU registers. The exact details vary by processor, compiler and ABI.</p>

<p>But what exactly is being passed to <code>std::sort</code>? Well letâ€™s look at the original code</p>

<pre class="programlisting">
  std::sort(&amp;first,
    &amp;first + 1 + sizeof...(rest));</pre>

<ul>
	<li><code>&amp;first</code> is clearly the address of the first parameter.</li>
	
	<li><code>&amp;first + 1 + sizeof...(rest)</code> is the address of the end of the region to be sorted. This assumes that the region is contiguous starting at <code>&amp;first</code>. However, due to C++ calling conventions, this may or may not be true.</li>
</ul>

<p>Hence, the straight forward reason for differing behaviour of least, is that the parameters may not be in contiguous memory, hence <code>std::sort</code> may experience a memory access error.</p>

<p>Before, looking at possible solutions lets get another problem into the open. The student wants to find the smallest number of a supplied set by sorting the set and taking the first element of the sorted set. This at best is going to be of order O(NlogN), and we have absolutely no interest in the rest of the sorted set beyond the smallest. Using <code>std::min</code> to find the smallest element is of order O(N) and we do not need to carry any additional information around.</p>

<p>To recap, we need to find the smallest element of a set of numbers supplied as parameters to a variadic function, without any memory â€˜gapsâ€™ due to the calling convention. There are two possible approaches, viz.: recursion on the rest parameter or use <code>std::initializer_list</code>. <code>initializer_list</code> guarantees that its memory is contiguous.</p>
<p>Letâ€™s start with the recursive approach, we will call the procedure <code>least_r</code>. As with all recursive processes, we need a base case, which for this problem must be one item, as in the sample code. That is just</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  inline T least_r(T first) { 
    // single input, so just return it
    return first;
  }</pre>
  
<p>That is easy. Now for the recursive case</p>

<pre class="programlisting">
  template &lt;typename T, typename... Ts&gt;
  T least_r(T first, Ts... rest) {
    // to prevent non-contiguous memory access, 
    // we peel the arguments off in turn
    return std::min(first, least_r(rest...));
  }</pre>
  
<p>The second approach, using <code>std::initializer_list</code> is just as simple. We will call this procedure <code>least_il</code> for<code>initializer_list</code>.</p>
 
<pre class="programlisting">
  template &lt;typename T, typename... Ts&gt;
  T least_il(T first, Ts... rest) {
    // to prevent non-contiguous memory access, 
    // we must create an initializer list
    const std::initializer_list&lt;T&gt; il {first,
      rest...};
    return std::min(il);
  }</pre>
  
<p>Both methods work, with the sample inputs and a set of 100 elements, and are acceptable to the <code>-fsanitize</code> test above. For added reassurance, both pass Clangâ€™s scan-build utility.</p>

<p>There is one more consideration, namely, efficiency. Whilst it is true that to use the <code>initializer_list</code> we have to make a complete copy of the input set, it runs quicker than the recursive version, because it does not have to keep calling a smaller version of itself.</p>

<h4>Note</h4>

<p class="bibliomixed"><a id="[W1]"></a>[1]	Strictly speaking, this is not an explicit requirement, rather the exact requirement is that random access to the container happens in constant time. In practice all containers satisfying the random access criteria are also contiguous. [<em>Ed: this is incorrect â€“ for instance</em> <code>std::deque</code><em> is a counter-example</em>] Being able to â€˜splitâ€™ memory on updating an iterator would be a challenge.</p>

<h3>James Holland</h3>

<p>I can see that the student is trying to use <code>std::sort()</code> to iterate through the parameters of <code>least()</code> in order to find the one with the lowest value. Unfortunately, the code relies on the parameters being stored contiguously starting with first. This may not be the case and is not guaranteed by the standard. One way around this problem is to copy the parameters into a container from which <code>std::sort()</code> can operate, as shown below.</p>

<pre class="programlisting">
  #include &lt;algorithm&gt;
  #include &lt;array&gt;
  #include &lt;iostream&gt;
  template &lt;typename T, typename... Ts&gt;
  T least(T first, Ts... rest)
  {
    std::array&lt;T, sizeof...(rest) + 1&gt; a{first,
      rest...};
    std::sort(a.begin(), a.end());
    return *a.begin();
  }</pre>
  
<p>The container I have chosen is of type <code>std::array</code> and is named <code>a</code>. In order to declare <code>a</code>, the type of its elements needs to be specified. This is conveniently provided by the template parameter <code>T</code>. The declaration of <code>a</code> also needs to specify the length of the array. The array has to accommodate however many parameters there are in the parameter pack rest plus the parameter <code>first</code>, and is simply calculated by the expression <code>sizeof...(rest) + 1</code>.</p>

<p>Finding the smallest value of the array does not require <code>std::sort()</code>. The algorithm <code>std::min_element()</code> will be faster and, in this case, slightly easier to use.</p>

<pre class="programlisting">
  template &lt;typename T, typename... Ts&gt;
  T least(T first, Ts... rest)
  {
    std::array&lt;T, sizeof...(rest) + 1&gt; a{first,
      rest...};
    return *std::min_element(a.begin(),
      a.end());
  }</pre>
  
<p>There is also a recursive approach that can be used to find the minimum value as shown below.</p>

<pre class="programlisting">
  #include &lt;algorithm&gt;
  #include &lt;iostream&gt;
  template &lt;typename T&gt;
  T least(T first)
  {
    return first;
  }
  template &lt;typename T, typename... Ts&gt;
  T least(T first, Ts... rest)
  {
    return std::min(first, least(rest...));
  }</pre>
  
<p>When <code>least()</code> is called with more than one parameter, the version with the parameter pack is invoked. The returned value is the minimum of its first parameter and the minimum of all the other parameters. The minimum value of all the other parameters is obtained by calling <code>least()</code> again but this time not including the first parameter. This recursive arrangement keeps going until <code>least()</code> is called with just one parameter, at which point the version without the parameter pack is invoked. This version simply returns its parameter (the minimum of just one value is the value itself). Eventually, when all the invocations of <code>least()</code> have returned, the minimum value of the entire sequence is obtained.</p>

<p>It is interesting to note that although I have described this technique as being recursive, it is only recursive from a source code point of view. The compiler generates a series of <code>least()</code> functions each with a different number of parameters ranging from 1 to <em>n</em> where <em>n</em> is the number of elements in the sequence. Which one is called depends on the number of parameters provided. In this way, when <code>least()</code> â€˜recursesâ€™ it is a different function that is called each time.</p>

<p>It is possible to do away with the recursion and let <code>std::min()</code> operate on the whole sequence in one go as shown in my final version of <code>least()</code> below.</p>

<pre class="programlisting">
  template &lt;typename... Ts&gt; 
  auto least(Ts... all)
  {
    return std::min({all...});
  }</pre>
  
<p>Here, the parameter pack is expanded and used to create an unnamed object of type <code>std::initializer_list</code> that is passed to <code>std::min()</code>. The return type of <code>least()</code> is automatically deduced.</p>

<h3>Jason Spencer</h3>

<p>The headline bug of the unreliability of this code is down to function calling conventions for different platforms/languages/architectures.</p>

<p>Specifically, the greater number of registers available on 64-bit CPUs may mean the compiler passes function arguments in registers rather than on the stack, so we canâ€™t use pointer magic to calculate the end iterator.</p>

<p>The issue can be seen by entering the following program in to Matt Godboltâ€™s Compiler Explorer <a href="#[1]">[1]</a>:</p>

<pre class="programlisting">
  A0&gt; int fn (int a, int b, int c, int d, int e,
      int f, int g) {
  A1&gt; 
  A2&gt;     return (a+b+c+d+e+f+g);
  A3&gt; }
  A4&gt; int main() {
  A5&gt;      return fn(1,2,3,4,5,6,7);
  A6&gt; }
</pre>

<p>With the x86-64 gcc 8.1 compiler and no switches (therefore defaulting to amd64) the call looks like:</p>

<pre class="programlisting">
  B0&gt; push    7
  B1&gt; mov     r9d, 6
  B2&gt; mov     r8d, 5
  B3&gt; mov     ecx, 4
  B4&gt; mov     edx, 3
  B5&gt; mov     esi, 2
  B6&gt; mov     edi, 1
  B7&gt; call fn(int, int, int, int, int, int, int)
  B8&gt; add     rsp, 8
  B9&gt; nop</pre>
  
<p>The first six arguments are copied to registers (lines B1 to B6), but the seventh, the literal 7, is pushed to the stack (line B0).</p>

<p>When compiled with the same compiler and the <code>-m32</code> switch (telling the compiler to generate a binary for x86) the call looks like this:</p>

<pre class="programlisting">
  C0&gt; sub     esp, 4
  C1&gt; push    7
  C2&gt; push    6
  C3&gt; push    5
  C4&gt; push    4
  C5&gt; push    3
  C6&gt; push    2
  C7&gt; push    1
  C8&gt; call fn(int, int, int, int, int, int, int)
  C9&gt; add     esp, 32
  CA&gt; nop</pre>
  
<p>The subtraction in line C0 is to keep the stack pointer correctly aligned (on x86 the <code>esp</code> value has to be aligned to a 16 byte boundary at the function call).</p>

<p>The return value in both cases is returned in register EAX.</p>

<p>Lines B8 and C9 put the stack pointer to where it was before, effectively wiping that part of the stack used to transfer arguments.</p>

<p>C++ templates are instantiated at compile time, and the same template, but with a different number of arguments, is effectively a different function (which is why some people complain that templates cause &quot;code bloat&quot;).</p>

<p>As such the instantiation, aka function, with four arguments may have all arguments reside in registers, on both x86 and amd64, but the function with 10 arguments will have some on the stack and some in registers.</p>

<p>The bit thatâ€™s missing from the above snippets is what happens to the passed arguments in the <em>called</em> function. They can be pushed from the registers on to the stack, which is what actually happened in the case above (but not shown here), but that is not always the case.</p>

<p>So why do we care about how itâ€™s passed? Well, in the studentâ€™s <code>least</code> templated function we take the address of the first argument and we use that as the start iterator passed to <code>std::sort</code>, and from that we do some arithmetic to find the end iterator (the one after the last element). But because of the calling conventions, and because we are dealing with raw pointers, the elements to be sorted may not be contiguous in memory and they may also be in registers. The arguments could also be pushed on the stack in reverse order (but thatâ€™s not what happens above since the stack grows â€˜downwardsâ€™ in memory, hence the add in C9 and B8 actually unwinds the stack). If you attempt to take the address of one of the arguments, ie <code>&amp;first</code>, and it is in a register, then the compiler will copy it first to the stack â€“ but the other elements it may not.</p>

<p>Donâ€™t take this is as a hard rule, though â€“ the way arguments are passed and whether the calling or the called function does the cleanup depends on a number of things, not just the CPU architecture, and can change between OSes, the language, the compiler, and even compiler version â€“ see <a href="#[2]">[2]</a>, <a href="#[3]">[3]</a>, <a href="#[4]">[4]</a>, <a href="#[5]">[5]</a>, <a href="#[6]">[6]</a> and <a href="#[7]">[7]</a> for more details. You can also add attributes to functions to change the calling convention on a per-function basis, for example <a href="#[8]">[8]</a>. It is these differences that causes problems for the student.</p>

<p>Also, since weâ€™re dealing with literal values, when optimisation is enabled most compilers will calculate the least value at compile time, rather than at runtime anyway (and magically work!).</p>

<p>Put simply, you should never ever make such assumptions about the calling conventions.</p>

<p>A few other things stand out straight away in the studentâ€™s code:</p>

<ul>
	<li>The code unnecessarily uses sort to get the lowest value. <code>std::sort</code> is guaranteed to be O(N ln N) in time complexity, but we donâ€™t need all of the values sorted, we just need the lowest value. To do this we can simply scan through the values keeping a record of which is the lowest value. This can be done in O(N) since each value has to be checked only once.</li>
	
	<li>The use of pass by copy â€“ this requires the type to be copyable â€“ fine if itâ€™s a POD (plain-old-datatype), not so much if itâ€™s a UDT (user-defined-type). Prefer to pass by const reference or const copy (the latter <em>may</em> lead to copy elision, in some circumstances).</li>
	
	<li>There is a potential <code>reinterpret_cast</code> of arguments: <code>std::sort </code>deduces the type of the elements being sorted from the iterators being passed to it (they must both have the same type). With a variadic template, the type of each argument can be different. So if the first argument is a <code>char</code> (say, one byte in size) and the remaining three arguments are <code>long long</code> (say, 8 bytes), then the type to be sorted is deduced as <code>char</code> but the end iterator points to the <code>char</code> four (1+sizeof...(rest) =&gt; 1+3) <strong>bytes</strong> later, which is not even the whole way through the first <code>long long</code> argument. And the bytes extracted from the first <code>long long</code> argument are effectively nonsense anyway. The precise values are dependant on the endianess of the architecture. This wasnâ€™t seen here because the literal digits were assumed to be of type <code>int</code>, but adding a <code>float</code> in the middle will easily corrupt the result.</li>
	
	<li>And the elephant in the room is that the least function is already part of the STL since C++14: <code>template&lt; class T &gt; constexpr T min( std::initializer_list&lt;T&gt; ilist );</code> Bear in mind, though, that <code>initializer_lists</code> pass by copy, so <code>T</code> has to be again copyable.</li>
</ul>

<p>As to an alternative implementationâ€¦ I donâ€™t knowâ€¦ it all depends on what you really want from it.</p>

<p>To go completely the other way from a pass-by-copy function, and if youâ€™re particularly weird, you could pass by universal reference everywhere and return such a reference, so you could write a function that will let you overwrite the left-most lowest value:</p>

<pre class="programlisting">
  template &lt;typename T&gt; T&amp;&amp; least(T&amp;&amp; first) {
    return (std::forward&lt;T&gt;(first));
  }
  template &lt;typename T, typename... Ts&gt; T&amp;&amp;
    least(T&amp;&amp; first, Ts&amp;&amp;... rest)
  {
    auto &amp;&amp; l =
      least(std::forward&lt;Ts&gt;(rest)...);
    return std::forward&lt;T&gt;(((first &lt;= l ) ?
      first : l));
  }</pre>
  
<p>The template here starts from the last value and works forward, so make the ternary test <code>(first &lt; l )</code> if you want a reference to the right-most lowest value. And obviously <code>&gt;=</code> if you want your <code>least</code> function to perform a left-most <code>most</code> search.</p>

<p>So now that weâ€™re dealing with references we can do weird things like this:</p>

<pre class="programlisting">
  int main() {
  int a = 3, b = 1, c = 2, d = 0;
  std::cout &lt;&lt; &quot;Before : &quot; &lt;&lt; a &lt;&lt; ',' &lt;&lt; b &lt;&lt;
    ',' &lt;&lt; c &lt;&lt; ',' &lt;&lt; d &lt;&lt; '\n';	
  least(a,b,c,-1,d) = 42;
  std::cout &lt;&lt; &quot;TP1 : &quot; &lt;&lt; a &lt;&lt; ',' &lt;&lt; b &lt;&lt;
    ',' &lt;&lt; c &lt;&lt; ',' &lt;&lt; d &lt;&lt;'\n';	
  least(a,b,c,d) = 42;
  std::cout &lt;&lt; &quot;TP2 : &quot; &lt;&lt; a &lt;&lt; ',' &lt;&lt; b &lt;&lt;
    ',' &lt;&lt; c &lt;&lt; ',' &lt;&lt; d &lt;&lt;'\n';	
  std::cout &lt;&lt; &quot;TP3 : &quot; &lt;&lt; least(2,3,4,5,6,78,9)
    &lt;&lt; '\n';
  }</pre>

<p>Where the output is:</p>

<pre class="programlisting">
  $ ./a.out 
  Before : 3,1,2,0
  TP1 : 3,1,2,0
  TP2 : 3,1,2,42
  TP3 : 2
  $</pre>
  
<p>So now <code>least</code> returns a reference to the lowest value and we can overwrite it. I think this is iffy for a few reasons, the least of which is that it might be confusing as to what the function really does.</p>

<p>Another issue is that the type of each argument can be different and the values may undergo a narrowing conversion (by implicit cast) to different types with loss of precision in the less than comparison. For example, <code>least ( 0.9, 2, 3, 4 )</code> will return 0.9, but <code>least ( 1, 2, 3, 0.9 )</code> will return 0.</p>

<p>My preferred approach, however, is to decompose the problem â€“ weâ€™re reducing/folding according to some operator. So why not implement a fold/reduce template, pass the reduction operation as a parameter and let the compiler do the heavy lifting. Of course C++17 also has fold expressions.. but they only work for a handful of operators (+, -, * etc) and we can forsake the syntactic sugar of fold expressions and go further with a customisable reduction.</p>

<p>So letâ€™s create a template thatâ€™ll do our reduction and which takes the reducing functor as a parameter:</p>

<pre class="programlisting">
  template &lt; typename OP&gt; struct lfold {
  OP op;
  template &lt;typename T, typename... Ts&gt;
  constexpr const T operator()(const T &amp; first,
    const T &amp; second, const Ts&amp;... rest)
  {
    if constexpr ( sizeof...(rest) == 0 )
      return op(first, second);
    else
      return operator()(op(first, second),
        rest...);
  }
  };</pre>
  
<p>Weâ€™re returning by copy deliberately â€“ because <code>op</code> may not be returning a reference, and may be returning a temporary.</p>

<p>Weâ€™re also using an <code>if constexpr</code> so we only need one template. Note also weâ€™re taking two arguments at a time, and the adjacent arguments must have the same type, so they effectively all have to be the same type. Passing a series of <code>int</code>s and a <code>double</code> will cause a compile error, rather than a silent implicit conversion.</p>

<p>We could now write a functor that returns the lower of two values and be done with itâ€¦ instead letâ€™s write a functor that selects one argument according to a comparator that is provided as a parameter:</p>

<pre class="programlisting">
  template &lt; typename CMP &gt; struct selector {
  CMP cmp;
  template &lt;typename T&gt; constexpr T &amp;
    operator()( T &amp; first, T &amp; second )
  {
    return (cmp(first,second)?first:second);
  }
  };</pre>
  
<p>Ok, so now we can do something like this:</p>

<pre class="programlisting">
   using least =
    lfold &lt; selector&lt;std::less&lt;void&gt;&gt; &gt;;
  using most =
    lfold &lt; selector&lt;std::greater&lt;void&gt;&gt; &gt;;</pre>
	
<p>Note the use of <code>void</code> as the template parameter â€“ since C++14, this means that the type deduction is deferred, so it means we donâ€™t have to provide an explicit type in the <code>typedef</code>.</p>

<p>Now that we have a general-purpose reduction template we can also do things like:</p>

<pre class="programlisting">
  using sumer = lfold &lt; std::plus&lt;void&gt; &gt;;
  using producter =
    lfold &lt; std::multiplies&lt;void&gt; &gt;;</pre>
	
<p>And it gets crazier â€“ <code>std::plus</code> works on anything that has an <code>operator+</code> overload, so we could even concatenate strings:</p>

<pre class="programlisting">
  using namespace std::string_literals;
  std::cout &lt;&lt; sumer{}(&quot;a&quot;s,&quot;b&quot;s,&quot;c&quot;s,&quot;d&quot;s)
    &lt;&lt; '\n';</pre>
	
<p>outputs <code>abcd</code>.</p>

<p>Note, though, that the order of summing is significant when the type is a stringâ€¦ which is why our reduction template is called <code>lfold</code> (left fold). A right fold would look like:</p>

<pre class="programlisting">
  template &lt; typename OP&gt; struct rfold {
  OP op;
  template &lt;typename T, typename... Ts&gt;
    constexpr const T operator()(
      const T &amp; first, const T &amp; second,
      const Ts&amp;... rest)
  {
    if constexpr ( sizeof...(rest) == 0 )
      return op(second, first);
    else
      return op(operator()(second, rest...),
        first);
  }
  };</pre>
  
<p>And with:</p>

<pre class="programlisting">
  using rsumer = rfold &lt; std::plus&lt;void&gt; &gt;;
  std::cout &lt;&lt; rsumer{}(&quot;a&quot;s,&quot;b&quot;s,&quot;c&quot;s,&quot;d&quot;s)
    &lt;&lt; '\n';</pre>
	
<p>would output <code>dcba</code>.</p>

<p>If the creation of a least, most, rsumer, sumer, etc. temporary (through the use of <code>{}</code> initialisation) is not acceptable then there may be mileage in calling the <code>operator()</code> from a variadic template constructor which takes the actual arguments, and the temporary object returns the result by a conversion operator. I prefer the approach above, however, because we can initialise the reduction operator and we can do things like this:</p>

<pre class="programlisting">
  struct ewma_op {
    double ewma;
    template &lt;typename T&gt; constexpr T
      operator()(const T &amp; data1,
        const T &amp; data2) {
      return (((1.0-ewma)*data1) +
       (ewma*data2));
      }
  };
  using ewma = lfold &lt; ewma_op &gt;;
  std::cout &lt;&lt; ewma{0.1}(0.1,0.2,0.3,0.4)
    &lt;&lt; '\n';</pre>
	
<p>The last line calculates the exponential weighted moving average of the arguments with a smoothing co-efficient of 0.1.</p>

<p>The <code>{0.1}</code> is used to initialise the <code>lfold::op</code>â€¦ which is also a struct that supports brace initialisationâ€¦ so that value is used to set <code>ewma_op::ewma</code>â€¦ and we can magically set the smoothing co-efficient.</p>

<p>And the coolest thing about this (if you supply literals, and depending on the types used) is that itâ€™s <code>constexpr</code> and the compiler will optimise out much of it, even finding the entire result at compile time and thereâ€™ll be no runtime cost.</p>

<p>You could also use <code>lfold</code> with a <code>hash_combine_op</code> that is initialised with a seed, then takes a list of arguments for reduction, calculates the hash (with a hash function specified as a template parameter), combines the hash value (see <code>boost:hash_combine</code>) with the seed and continues (thanks to <code>lfold</code>) through the list of arguments.</p>

<p>But for now, I think that solves the original problem.</p>

<h4>References</h4>

<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="https://gcc.godbolt.org/">https://gcc.godbolt.org/</a></p>

<p class="bibliomixed"><a id="[2]"></a>[2]	<a href="https://en.wikipedia.org/wiki/Application_binary_interface">https://en.wikipedia.org/wiki/Application_binary_interface</a></p>

<p class="bibliomixed"><a id="[3]"></a>[3]	<a href="https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64">https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	<a href="https://www.agner.org/optimize/calling_conventions.pdf">https://www.agner.org/optimize/calling_conventions.pdf</a></p>

<p class="bibliomixed"><a id="[5]"></a>[5]	<a href="https://software.intel.com/en-us/node/682402">https://software.intel.com/en-us/node/682402</a></p>

<p class="bibliomixed"><a id="[6]"></a>[6]	<a href="https://en.wikipedia.org/wiki/X86_calling_conventions">https://en.wikipedia.org/wiki/X86_calling_conventions</a></p>

<p class="bibliomixed"><a id="[7]"></a>[7]	<a href="https://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions">https://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions</a></p>

<p class="bibliomixed"><a id="[8]"></a>[8]	<a href="https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html">https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html</a></p>

<h2>Commentary</h2>

<p>The code in this critique relies on being able to sort a set of function arguments as if they were a range. As all our entries pointed out to greater or lesser extent, this assumption is flawed in a number of ways.</p>

<p>Firstly, the standard requires that a range refers to a single C++ object, so irrespective of the specifics of the implementation treating the <em>separate</em> objects as a range is <strong>undefined</strong> behaviour.</p>

<p>Secondly, the code is assuming that the arguments are contiguous in memory with increasing addresses. While this may be true in some cases â€“ for example on some platforms with un-optimized 32bit calls using the default calling convention â€“ it is not in general true. Some calling conventions push pass the arguments left-to-right, other push them right-to-left, and in many calling conventions the first few arguments are passed in registers and others are passed on the stack; if the address of one of the former arguments is taken then the register value will be copied into a memory location and its address will be used. This address may have no obvious relationship to the addresses of the arguments passed on the stack!</p>

<p>Thirdly, the code is assuming that the arguments are the same size as the amount of stack that they consume. So, even on a 32-bit platform, the original code was highly likely to fail if called with char arguments.</p>

<p>As everyone noticed, the code did too much work in that the whole range was sorted although only the single least value was required. Over the years I have noticed a number of places that used <code>std::sort</code> when only a small part of the sorted output was being used; there are other algorithms that can be used such as <code>std::partial_sort</code>.</p>

<p>One open question is what the code should do with arguments of different type. The code provided would <em>accept</em> them but do the wrong thing. As is common with these critiques, and is also the case for many of us in our working life, thereâ€™s no formal specification.</p>

<h2>Postscripts to recent Code Critique competitions</h2>

<p>Jason Spencer has sent us some reflections and updates to his entries.</p>

<h3>Postscript to Code Critique 111</h3>

<p>In an attack of involuntary stupidity, not only did I not comment on the sequence point issue in Code Critique 111 but â€“ even worse â€“ I made the mistake myself! I spotted it in the first pass when looking at the Code Critique, but then I context switched to other languages while doing the write-up. Itâ€™s down to an annoyance between many C-like languages â€“ they look similar, but they donâ€™t always act similar. Java, C# and Javascript would interpret:</p>

<pre class="programlisting">
  a = 42;
  a = ++a + a++;</pre>
  
<p>as:</p>

<pre class="programlisting">
  a = 43 + a++;
  a = 43 + 43; // but a is 44 (because of the post-
               // increment) before it is assigned
               // the value of the summation
  a = 86;      // and a is now 86, overwriting the
               // 44 value in a</pre>
			   
<p>Thatâ€™s because they guarantee (to the best of my knowledge) to <em>evaluate</em> expressions from left to right once operator precedence has been taken into consideration. Because the assignment operator has a low precedence and right-to-left associativity the expression on the right of the operator will be computed first.</p>

<p>C and C++ do not guarantee the order in which expressions are evaluated.</p>

<p>The good news is that g++ flags this as undefined behaviour when invoked with the <code>-Wall</code> or <code>-Wsequence-point</code> switch, but clang++ and VS donâ€™t complain, even with <code>-Wall</code> /<code>Wall</code>.</p>

<p>In practice, it looks like this:</p>

<table>
	<tr>
		<td>VC++</td>
		<td>-</td>
		<td>87</td>
	</tr>
	
	<tr>
		<td>VC++</td>
		<td>-O3</td>
		<td>87</td>
	</tr>
	
	<tr>
		<td>g++</td>
		<td>-</td>
		<td>87</td>
	</tr>
	
	<tr>
		<td>g++</td>
		<td>-O3</td>
		<td>87</td>
	</tr>
	
	<tr>
		<td>clang</td>
		<td>-</td>
		<td>86</td>
	</tr>
	
	<tr>
		<td>clang</td>
		<td>-O3</td>
		<td>86</td>
	</tr>
	
	<tr>
		<td>ICC</td>
		<td>-</td>
		<td>86</td>
	</tr>
	
	<tr>
		<td>ICC</td>
		<td>-O3</td>
		<td>86</td>
	</tr>	

</table>

<p>Alas, I donâ€™t have the compiler versions to hand, but you get the point â€“different compilers use different ordering of evaluation as itâ€™s not guaranteed by the standard. Check out godbolt.org to try the code snippet above.</p>

<p>Mistakes like this are a good reason to spread out code and program in a more defensive and explicit way, with the increment on a line of its own.</p>

<h3>Postscript to Code Critique 109</h3>

<p>While working towards a <code>zipit::operator*</code> implementation, I mimicked <code>std::vector&lt;bool&gt;::reference</code> by implementing a proxy object which acts like a reference.</p>

<p>Throwing caution to the wind, in a spasm of flippancy, I suggested an implementation of <code>operator-&gt;</code> technically could (but itâ€™s really ugly and it shouldnâ€™t) return a (smart) pointer to a dynamically allocated proxy object.</p>

<p><code>vector&lt;bool&gt;</code> does not do this, nor Boost.ZipIterator, and for good reason â€“ itâ€™s not only hideous, itâ€™s also against the specs.</p>

<p>It has come to my attention through a discussion between Niels Dekker and Anthony Williams on the accu-general mailing list that in fact the C++ specification requires <code>operator-&gt;</code> to return a raw pointer, which would forbid the use of a proxy object. So the idea of returning a smart pointer to a proxy object is even more wrong.</p>

<p>Right, now I need to go and boil my head.</p>

<h2>The winner of Code Critique 113</h2>

<p>The critiques all identified the problem and proposed alternative approaches without the troublesome behaviour. I found Stewartâ€™s phrasing of the difference between the size of an <code>int</code> and the size of a stack word to explain why the code doesnâ€™t work on 64bits particularly clear,</p>

<p>I like Joe Woodâ€™s mention of using sanitizers to help debug the problem: there are a lot of good tools out there to help with identifying problematic code in an automated fashion.</p>

<p>Jason Spencer provided some very nice examples of where you might take this technique further (although the universal reference version of least may behave unexpectedly if the returned reference is to a temporary.) The suggestion of using godbolt is a good idea to help see the generated output in a readable format.</p>

<p>I liked James Hollandâ€™s final version of his solution to the problem, which simply provides a forward to the standard <code>min</code> function taking an <code>initializer_list</code>. This solution makes great use of pre-existing standard facilities.</p>

<p>Stewart provides a good dialogue as he works towards his solution, and I think many programmers would find this approach would not only help them to understand the solution, but also <em>how</em> one might reach such a solution.</p>

<p>After some deliberation on the strengths of the various entries, I have awarded this issueâ€™s prize to Stewart.</p>

<h2>Code Critique 114</h2>

<p>(Submissions to scc@accu.org by Dec 1st)</p>

<p class="blockquote">I am trying to write a simple test for some C++17 code, but I am getting some unexpected output. I have simplified the code quite a bit, and in the resultant code below I was expecting to see the output &quot;A,B&quot; but on the latest version of both gcc and MSVC I get just &quot;AB&quot;. Where has my comma gone?! Even more oddly, if I use an older compiler I get different output: &quot;65,66&quot;, which gives me back the comma but loses the letters. Has C++17 broken something?</p>

<p>The code is in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
template &lt;typename T&gt;
using coll = std::vector&lt;T&gt;;
// Start the collection
template &lt;typename T&gt;
void start(coll&lt;T&gt; &amp;up)
{
  up.clear();
}
// End the collection
template &lt;typename T&gt;
void end(coll&lt;T&gt; &amp;up)
{
  up.push_back({});
}
// Extract the non-zero data as a string
template &lt;typename T&gt;
std::string data(coll&lt;T&gt; const &amp;up)
{
  std::string result;
  for (auto v : up)
  {
    if (v)
    {
      result += std::to_string(v);
      result += &quot;,&quot;;
    }
  }
  result.pop_back();
  return result;
}
void test_char()
{
  auto i2 = coll&lt;char&gt;();
  start(i2);
  i2.push_back('A');
  i2.push_back('B');
  end(i2);
  // actual test code elided
  std::cout &lt;&lt; data(i2) &lt;&lt; '\n';
}
int main()
{
  test_char();
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>You can also get the current problem from the accu-general mail list (next entry is posted around the last issueâ€™s deadline) or from the ACCU website (<a href="http://accu.org/index.php/journal">http://accu.org/index.php/journal</a>).</p>

<p>This particularly helps overseas members who typically get the magazine much later than members in the UK and Europe.</p>


<p class="bio"><span class="author"><b>Roger Orr</b></span>  Roger has been programming for over 20 years, most recently in C++ and Java for various investment banks in Canary Wharf and the City. He joined ACCU in 1999 and the BSI C++ panel in 2002.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
