function parameters that are writeable only by the function itself - recursion counter - c++

So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).

You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.

If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}

You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);

One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.

Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.

Related

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

C++ Calling function inside another function that uses references and parameters

I'm programming at Arduino IDE (that uses basically C++) and I'm in trouble to call a function inside another. The part of code is below:
unsigned long int deslocamento (char sentido, byte &cont, const int pino, unsigned long int posicaoA)
{
byte leitura;
unsigned int deltaposicao;
leitura = digitalRead(pino);
if ((leitura == HIGH) && (cont == 0))
{
cont = 1;
}
if ((leitura == LOW) && (cont == 1))
{
cont = 0;
deltaposicao++;
}
if (sentido == 'F')
{
posicaoA += deltaposicao;
}
else
{
posicaoA -= deltaposicao;
}
return posicaoA;
}
void zeramento (unsigned long int posicaoA)
{
byte pwm = 255;
char sentido = 'R';
byte fator;
fator = fatorcorrecaoP (pwm);
while (posicaoA != 0)
{
posicaoA = deslocamento (sentido, cont, pinencoder, posicaoA);
posicaoA -= fator;
comando (sentido, pwm);
}
}
On function "void zeramento" should I declare as inputs all the inputs (parameters) that function "unsigned long int deslocamento" uses too or have an easier and shorter (or maybe a more efficient in therms of memory optimization) way to do that? For example, should I declare as "void zeramento(posicaoA, sentido, &cont, pinecoder)"?
Thanks for all and sorry for any problem. I'm new here and still learning English.
It depends on what you are trying to achieve. For a shorter code, I'll just call your functions funcA and funcB and the parameters par1 and par2.
You can do either
void funcA(int par1, int par2)
{ ... use par1 and par2 ... }
void funcB(int par1, int par2)
{
...
funcA(par1, par2);
...
}
or
int global_par1;
int global_par2;
void funcA(int par1, int par2)
{ ... use par1 and par2 ... }
void funcB()
{
...
funcA(global_par1, global_par2);
...
}
In the first case you only use local variables, while in the second you use global ones.
The difference is that in the global case (please call them differently in funcA and funcB, since there could be readability issues) the variables are unique for the whole program (i.e. if you modify them in the main you will modify them even in the functions), while in the local case you are just working on a local copy of them.
In my opinion, since these variables identify the position (which is unique) I'd go with a fully global solution, i.e.
int global_par1;
int global_par2;
void funcA()
{ .. use global_par1 and global_par2.. }
void funcB()
{
...
funcA();
...
}

How does one declare a variable inside an if () statement? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Declaring and initializing a variable in a Conditional or Control statement in C++
Instead of this...
int value = get_value();
if ( value > 100 )
{
// Do something with value.
}
... is it possible to reduce the scope of value to only where it is needed:
if ( int value = get_value() > 100 )
{
// Obviously this doesn't work. get_value() > 100 returns true,
// which is implicitly converted to 1 and assigned to value.
}
If you want specific scope for value, you can introduce a scope block.
#include <iostream>
int get_value() {
return 101;
}
int main() {
{
int value = get_value();
if(value > 100)
std::cout << "Hey!";
} //value out of scope
}
Can you declare a variable and compare it within the if() statement? No.
Can you declare a variable and compare it in such a way that the scope is tightly-bound to the if() block? Yes!
You can either declare a variable:
if (int x = 5) {
// lol!
}
or you can do things with one:
int x = foo();
if (x == 5) {
// wahey!
}
You can't do both!
You can cheat a little where the only thing you need to do is compare with true, because the declaration itself evaluates to the value of the new object.
So, if you have:
int foo()
{
return 0;
}
Then this:
if (int x = foo()) {
// never reached
}
is equivalent to:
{
int x = foo();
if (x) {
// never reached
}
}
This final syntax, using a standalone scope block, is also your golden bullet for more complex expressions:
{
int x = foo();
if (x > bar()) {
// wahooza!
}
}
Put it in a function:
void goodName(int value) {
if(value > 100) {
// Do something with value.
}
}
//...
goodName(get_value());
How about using for instead?
for (int value = get_value(); value > 100; value = 0) {
//...
}
If you want to go C++11 on it, you can use a lambda:
[](int value = get_value()) {
if (value > 100) {
//...
std::cout << "value:" << value;
}
}();
Or you could just add an extra set of braces for a nested scope, although it's not exactly pretty:
{
int value = get_value();
if ( value > 100 )
{
// Do something with value.
}
}
//now value is out of scope
You can write a small function which can do the comparison for you and return the value the if comparison returns true, else return 0 to avoid executing the if block:
int greater_than(int right, int left)
{
return left > right ? left : 0;
}
Then use it as:
if ( int value = greater_than(100, get_value()))
{
//wow!
}
Or you can use for as other answer said. Or manually put braces to reduce the scope of the variable.
At any rate, I would not write such code in production code.
Don't write code for machines. Write code for humans. Machines will understand anything as long as you follow their grammar; humans understand what is readable to them. So readability should be your priority over unnecessary scoping.
In this particular case, you can bodge it:
if (int value = (get_value() > 100 ? get_value() : 0)) {
...
}
I don't really recommend it, though. It doesn't work for all possible tests that you might want to perform, and it calls get_value() twice.

a way to test if you're on the first run of several recursive calls c++

I'm was wondering if there's a way to check if you're on the first recursive call of a series of many recursive calls.
I'm working on a function that tests to see if the input is a palindrome. After the last recursive call is over, the input string is changed to to the reverse of the original. Now all I want to do is compare the result with the original. But when the base case is reached, I no longer have access to the copy of the original string I made in the else statement.
My thought is then to compare palCopy with palCheck under the else statement but the problem with that is that the program will check this during EVERY recursive call when I only want to check it when control is returned to the original recursive call. Is there a way to conditionally compare palCopy and palCheck only when control is returned to the original recursive call?
void isAPalindrome(MyString palCheck, int bound1, int bound2)
{
if (bound1 >= bound2)
{
cout << palCheck;
}
else
{
MyString palCopy = palCheck; // make a copy of the original argument so as not to alter it
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindrome(palCopy, bound1 + 1, bound2 - 1);
}
C++ has no primitive way to know if you are in the first recursion. But you could use a level variable, that counts the recursion depth. Something like:
void isAPalindrome(MyString palCheck, int bound1, int bound2, int level=0)
{
if (bound1 >= bound2)
cout << palCheck;
else
{
MyString palCopy = palCheck;
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindrome(palCopy, bound1 + 1, bound2 - 1, level+1);
if (level == 0)
// You are in the first recursion call
}
}
In general you can track recursion depth by doing something like:
void recurse(int value, const int depth=0)
{
recurse(value, depth+1);
}
That is using an extra variable to for each of the calls which record the depth of recursion at any given point.
I wouldn't solve this problem this way, but never mind that. The general way to do something like this is to move the recursion into a helper function that takes an extra argument:
static void
is_palindrome_internal(string palCheck, int bound1, int bound2,
bool outermost)
{
...
is_palindrome_internal(..., false);
...
}
void
is_palindrome(string palCheck, int bound1, int bound2)
{
is_palindrome_internal(palCheck, bound1, bound2, true);
}
Then outermost will be true only when the current invocation is the outermost. This approach also has the advantage that you can hide the bound1 and bound2 arguments from the public API (only do this if you don't ever want to operate on substrings, of course).
void
is_palindrome(string palCheck)
{
is_palindrome_internal(palCheck, 0, palCheck.length(), true);
}
You are already passing one copy of string as an arg. You can also pass a reference to the original string so that all levels of recursion have access to both.
void isAPalindrome(MyString palCheck, int bound1, int bound2 , const MyString& original )
{
//Do stuff
isAPalindrome(palCopy, bound1 + 1, bound2 - 1,original);
}
I would use a local struct so that is_palindrome() will accept just one argument:
bool is_palindrome(const std::string& s)
{
struct local
{
static bool is_palin(const std::string& s, int l, int h)
{
return l>= h?true:(s[l] == s[h]? is_palin(s,l+1,h-1):false);
}
};
return local::is_palin(s, 0, s.size() - 1);
}
Online demo : http://www.ideone.com/o1m5C
Use and modify it whichever way you want to.
Make it a seperate function:
void isAPalindromeHelper(MyString& palCheck, int bound1, int bound2)
{
if (bound1 >= bound2)
{
cout << palCheck;
}
else
{
char temp = palCopy[bound1];
palCopy[bound1] = palCopy[bound2];
palCopy[bound2] = temp;
isAPalindromeHelper(palCopy, bound1 + 1, bound2 - 1);
}
}
void isAPalindrome(MyString palCheck)
{
MyString palCopy = palCheck;
isAPalindromeHelper(palCheck, 0, palCheck.size());
if (palCopy == palCheck)
//newstuff here
}

Hiding iteration in a function

Only got rough idea of what I want, perhaps someone could pad it out and/or tell me if its possible.
I would like to simplify my multiply nested loops, to that end I would like to be able to call a function (for example that uses boost::filesystem) that returns a file in a directory, each successive call would return the next file, until all were exhausted. Also i would like to be able to do this with a vector, and have the function return successive elements.
Any ideas how this could be done? thanks
Create a functor: an object that is called like a function.
The object will hold the query results and the current state of the query. You define an operator() so the object can be called as if it were a function. Each time this function is called you return one result and update the object's internal state.
Example:
#include <iostream>
using namespace std;
class CountDown {
unsigned count;
public:
CountDown(unsigned count) : count(count) {}
bool operator()() { return count-- > 0; }
};
int main()
{
CountDown cd(5);
while( cd() ) {
cout << "Counting" << endl;
}
return 0;
}
use Iterator pattern. In Java you'd have smth like this:
class FileIterator {
private int index;
private File[] files;
public FileIterator(File[] files) {
this.files = files;
this.index = 0;
}
public boolean hasNext() {
if (index < files.length - 1) {
return true;
} else {
return false;
}
}
public File next() {
return this.files [index ++];
}
}
and you'd use it like this:
FileIterator it = new FileIterator(theFiles);
while (it.hasNext()) {
File f = it.next();
}
You can use BOOST_FOREACH to simplify loops link to docs and stackoverflow