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

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();
...
}

Related

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

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.

Return from calling function inside lambda

Lambdas are an awesome way to create reusable code inside a function/method without polluting the parent class. They're a very functional replacement for C-style macros most of the time.
However, there's one bit of syntactic sugar from macros that I can't seem to replicate with a lambda, and that's the ability to exit from the containing function. For example, if I need to return while checking the range of a series of ints, I can do that easily with a macro:
const int xmin(1), xmax(5);
#define CHECK_RANGE(x) { if((x) < xmin || (x) > xmax) return false; }
bool myFunc(int myint) {
CHECK_RANGE(myint);
int anotherint = myint + 2;
CHECK_RANGE(anotherint);
return true;
}
Obviously this is an oversimplified example, but the basic premise is that I'm performing the same check over and over on different variables, and I think it's more readable to encapsulate the check and related exits. Still, I know that macros aren't very safe, especially when they get really complex. However, as far as I can tell, trying to do the equivalent lambda requires awkward additional checks like so:
const int xmin(1), xmax(5);
auto check_range = [&](int x) -> bool { return !(x < xmin || x > xmax); };
bool myFunc(int myint) {
if(!check_range(myint)) return false;
int anotherint = myint + 2;
if(!check_range(anotherint)) return false;
return true;
}
Is there a way to do this with a lambda? Or am I missing some alternative solution?
Edit: I recognize that returning from inside a macro is generally a bad idea unless significant precautions are taken. I'm just wondering if it's possible.
You are correct--there's no way to return from the caller from inside a lambda. Since a lambda can be captured and stored to be called later, from inside an arbitrary caller, doing so would result in unpredictable behavior.
class Foo
{
Foo(std::function<void(int)> const& callMeLater) : func(callMeLater) {}
void CallIt(int* arr, int count)
{
for (index = count; index--;)
func(count);
// do other stuff here.
}
std::function<void(int)> func;
};
int main()
{
auto find3 = [](int arr)
{
if (arr == 3)
return_from_caller; // making up syntax here.
};
Foo foo(find3);
};
Is there a way to do this with a lambda?
Not exactly like the macro but your lambda, instead of returning a bool, can throw a special exception (of type bool, by example)
auto check_range
= [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };
and the function myFunc() can intercept this special type
bool myFunc (int myint)
{
try
{
check_range(myint);
int anotherint = myint + 2;
check_range(anotherint);
return true;
}
catch ( bool e )
{ return e; }
}
For a single check_range() call, this is (I suppose) a bad idea; if you have a lot of calls, I suppose can be interesting.
The following is a full working example
#include <iostream>
constexpr int xmin{1}, xmax{5};
auto check_range
= [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };
bool myFunc (int myint)
{
try
{
check_range(myint);
int anotherint = myint + 2;
check_range(anotherint);
return true;
}
catch ( bool e )
{ return e; }
}
int main ()
{
std::cout << myFunc(0) << std::endl; // print 0
std::cout << myFunc(3) << std::endl; // print 1
std::cout << myFunc(7) << std::endl; // print 0
}
No better way to do this than just to use the return value of the lambda and then return from the calling function. Macros are ew for this.
As it stands in C++, that is the idiomatic way to exit from a function that uses another condition to determine whether or not to exit.
Not C++11, but people have hacked C++2a coroutines to basically do this.
It would look a bit like:
co_await check_range(foo);
where the co_await keyword indicates that in some cases, this coroutine could return early with an incomplete result. In your cases, this incomplete result would be non-resumabable error.
The playing around I saw was with optionals, and required using a shared ptr, but things may improve before it is standardized.

Same variable for different datatypes?

I have to call one simple functions with different datatypes in c++. eg,
void Test(enum value)
{
int x;
float y; // etc
if(value == INT)
{
// do some operation on x
}
else if(value == float)
{
// do SAME operation on y
}
else if(value == short)
{
// AGAIN SAME operation on short variable
}
.
.
.
}
Thus I want to eliminate the repetitive code for different datatypes ...
So , I tried to use macro ,depending on values of enum, to define same variable for different datatypes .. but then not able to differentiate between the MACROS
e.g.
void Test(enum value)
{
#if INT
typedef int datatype;
#elif FLOAT
typedef float datatype;
.
.
.
#endif
datatype x;
// Do operation on same variable
}
But now every time the first condition #if INT is getting true.
I tried to set different values of macro to differentiate but not working :(
Can anyone help me achieve the above thing.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//type generic method definition using templates
template <typename T>
void display(T arr[], int size) {
cout << "inside display " << endl;
for (int i= 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int a[10];
string s[10];
double d[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
d[i] = i + 0.1;
stringstream std;
std << "string - "<< i;
s[i] = std.str();
}
display(a, 10); //calling for integer array
display(s, 10); // calling for string array
display(d, 10); // calling for double array
return 0;
}
If you really want your function to be generic, template is the way to go. Above is the way to do and call the method from main method. This might be of some help for you to reuse a function for different types. Pick up any tutorial or C++ books for complete understanding on templates and get a grip of the full concepts. Cheers.
You can use templates to achieve you purpose.
Simply write a template function which take the value in the function argument which is of generic type and put the operational logic inside it. Now call the function with different data types.
I advice you to use function overloading:
void foo(int arg) { /* ... */ }
void foo(long arg) { /* ... */ }
void foo(float arg) { /* ... */ }
Supposing you want do the same operation with integer and long types you can eliminate the code repetition in this way:
void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }

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
}