title: When algorithm is placed inside loop it produces different results, C++
body: <p>I create the following algorithm in Rcpp and compile it in R.</p>
  <pre><code>// [[Rcpp::depends(RcppArmadillo)]]
  #include &lt;RcppArmadilloExtensions/sample.h&gt;
  
  // [[Rcpp::export]]
  
  arma::colvec Demo(arma::mat n, int K){
    
    arma::colvec N(K);
    
    for(int j=0; j&lt;K; ++j){
      for(int i=0; i&lt;(K-j); ++i){
        N[j] += accu(n.submat(i,0,i,j));
      }
    } 
    return N;
  }
  
  /***R
  K = 4
  n = cbind(c(1008, 5112, 1026, 25, 0), 0, 0, 0, 0)
  Demo(n,K)
  
  for(i in 1:3){
   print(Demo(n,K))
   print(K)
   print(n)
  }
  */
  </code></pre>
  <p>However, something really weird happens when I run it inside a loop.</p>
  <p>For example, if I have</p>
  <pre><code>&gt; K = 4
  &gt; n
       [,1] [,2] [,3] [,4] [,5]
  [1,] 1008    0    0    0    0
  [2,] 5112    0    0    0    0
  [3,] 1026    0    0    0    0
  [4,]   25    0    0    0    0
  [5,]    0    0    0    0    0
  </code></pre>
  <p>Then if I run the algorithm <code>Demo</code> a single time I receive the correct result</p>
  <pre><code>&gt; Demo(n,K)
       [,1]
  [1,] 7171
  [2,] 7146
  [3,] 6120
  [4,] 1008
  </code></pre>
  <p>However, if I run it multiple times inside a loop, it starts to behave weird</p>
  <pre><code>for(i in 1:3){
   print(Demo(n,K))
   print(K)
   print(n)
  }
      [,1]
  [1,] 7171
  [2,] 7146
  [3,] 6120
  [4,] 1008
  [1] 4
       [,1] [,2] [,3] [,4] [,5]
  [1,] 1008    0    0    0    0
  [2,] 5112    0    0    0    0
  [3,] 1026    0    0    0    0
  [4,]   25    0    0    0    0
  [5,]    0    0    0    0    0
        [,1]
  [1,] 14342
  [2,] 14292
  [3,] 12240
  [4,]  2016
  [1] 4
       [,1] [,2] [,3] [,4] [,5]
  [1,] 1008    0    0    0    0
  [2,] 5112    0    0    0    0
  [3,] 1026    0    0    0    0
  [4,]   25    0    0    0    0
  [5,]    0    0    0    0    0
        [,1]
  [1,] 21513
  [2,] 21438
  [3,] 18360
  [4,]  3024
  [1] 4
       [,1] [,2] [,3] [,4] [,5]
  [1,] 1008    0    0    0    0
  [2,] 5112    0    0    0    0
  [3,] 1026    0    0    0    0
  [4,]   25    0    0    0    0
  [5,]    0    0    0    0    0
  </code></pre>
  <p>In the first run, it computes it correctly, then in the second run it gives the correct output multiplied by 2, and in the third run, it gives the correct output multiplied by 3. But based on the algorithm steps, I do not see an obvious step that produces this kind of behavior.</p>
  <p>The correct output should have been</p>
  <pre><code>for(i in 1:3){
   print(Demo(n,K))
  }
       [,1]
  [1,] 7171
  [2,] 7146
  [3,] 6120
  [4,] 1008
       [,1]
  [1,] 7171
  [2,] 7146
  [3,] 6120
  [4,] 1008
       [,1]
  [1,] 7171
  [2,] 7146
  [3,] 6120
  [4,] 1008
  </code></pre>