-7

I am trying to create a counter. It counts each operation such as multiplication, addition, subtraction, division. Every time I try to cout the counter, it stays as zero.

Can anyone shed any light on what I am doing wrong?

A bulk of my code is missing so I can protect it from other classmates, however I have listed how many operations is in that section where the code would be.

long karatsuba(int num1, int num2, int &counter)
{
 if (num1 < 10 || num2 < 10)
 {
    counter++ // 1 operation
    return num1 * num2;
 }
 /* calculates the size of the number */
 ... 4 operations

 /* split the digit sequences about the middle */
 ... 4 operations

 /* 3 calls made to numbers approximately half the size */
 int z0 = karatsuba(..., ..., counter);
 int z1 = karatsuba(..., ..., counter);
 int z2 = karatsuba(..., ..., counter);


 return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
 int counter = 0;
 cout << karatsuba(123, 456, counter) << " " << counter << endl;

 cout << endl;
 system("Pause");
 return 0;
}
  • Please post actual, compilable code. The code above has syntax errors. In particular, where is `counter` declared? – wallyk Dec 06 '17 at 22:52
  • If the bulk of your code *can be removed* and still produce the problem state you're describing, you're *far, far* better off posting *that* as a complete problem source than posting uncompilable conjecture. And don't be surprised if you find the actual problem while reducing your code; it happens more often than you may think. – WhozCraig Dec 06 '17 at 22:59
  • The code I removed is not needed because it works fine. I completed that part of the assignment. Just implementing the counter to count every operation that is not working. – Danielx511 Dec 06 '17 at 23:43

1 Answers1

2

The problem is this line:

cout << karatsuba(123, 456, counter) << " " << counter << endl;

Try instead cout << karatsuba(123, 456, counter); cout << " " << counter << endl;

the problem is cout, count is still 0 when it prints.

acesar
  • 170
  • 4
  • I will test this! Thank you. – Danielx511 Dec 06 '17 at 23:43
  • It worked. Thank you very much. Makes perfect sense. – Danielx511 Dec 06 '17 at 23:47
  • +1, good catch! Might be worth mentioning though that it's not guaranteed that "*count is still 0 when it prints.*" This is in fact undefined behavior. See [this question](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) for more information. – scohe001 Dec 07 '17 at 00:29