3

My code:

#include <iostream>
#include <vector>
#include <algorithm>

int test_n(std::vector<int>::iterator b, std::vector<int>::iterator e, int &n)
{
    n++;    
    std::vector<int>::difference_type l = e-b;

    if (l<100) return std::accumulate(b, e, 0);

    std::vector<int>::iterator tmp = b + l/2;
    int nL = test_n(b, tmp, n);
    int nR = test_n(tmp, e, n);

    return nL + nR;
}

int main()
{
    int n=0;
    std::vector<int> v;

    for (int i=1; i<1000; i++) v.push_back(i);
    std::cout << test_n(v.begin(), v.end(), n) << " (n=" << n << ")\n";
    return 0;
}

Why is n not incremented at least once?

slashmais
  • 7,069
  • 9
  • 54
  • 80
  • 1
    What is your output and what do you expect? – bkausbk Oct 09 '13 at 10:11
  • 2
    It is printed before it is incremented. The order of evaluation of the arguments to the output stream isn't specified. Try printing `n` on the following line. – juanchopanza Oct 09 '13 at 10:11
  • @bkausbk: I'm playing with snippets, in this case wanting to count the number of recursive calls for no reason other than just because ;) – slashmais Oct 09 '13 at 10:18

1 Answers1

12

n is incremented. It's just that C++ doesn't have a fixed order of evaluating arguments in a statement. Therefore, in the statement where you call test_n (the std::cout line just before the end), the compiler probably decides first to check the value of n, and only then call test_n and get its output.

My advice: Separate the calls - do test_n before cout and you should see the change. So:

int testnresult = test_n(v.begin(), v.end(), n);
std::cout << testnresult  << " (n=" << n << ")\n";

See e.g. the question Compilers and argument order of evaluation in C++ for details on order in which arguments are evaluated in C++.

Community
  • 1
  • 1
codeling
  • 11,056
  • 4
  • 42
  • 71