How to transform a string in a function? - c++

Indeed I have this code :
#include <iostream>
double a(){return 1.23;}
double b(){return 1.21;}
int main(){
std::string function0;
return EXIT_SUCCESS;
}
And what I want is this : if function0 = 'a' I would like to be able to transform the string function0 in the function a but I don't know how to do this. If function0 is equals to b I would like to call the function b.
Thank you for your help !

What you want to do is calling one of the functions depending on the value of the string variable. This is easily achievable.
An if else construct in the main():
if (function0 == "a") {
foo = a();
} else if (function0 == "b") {
foo = b();
}
Merge the function and modify the result, so it behaves differently depending on the input:
double newFunction (string input) {
double valueForA = 1.23;
double valueForB = 1.21;
if (input == "a") {
return valueForA;
} else if (input == "b") {
return valueForB;
} else {
//what if it's not "a" nor "b"?
return 0;
}
}
Usage:
double foo = newFunction(function0);
N.B:
Don't neglect the return values of your function, if the returned value is not important use void function.
Learn to use variables (instead of useless functions). You could have created 2 variables in the main, and that would be it.
Visit this link to get started with C++. Without good references, you'll hate learning it, and that would be sad, or would it?
Stop using the book/website you're currently using to learn programming. It's (probably) garbage.

function pointers may help.
double (*funcPtr)();
int main() {
if (function0 == "a")
funcPtr = &a;
else
funcPtr = &b;
(*funcPtr)(); //calling a() or b()
}

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.

How can I print the variable that a void pointer points to

I would like the function to return different types depending on different parameter values, but how can I print the variable the void pointer points to
in main()?
#include <iostream>
#include <string>
using namespace std;
void * func(int a)
{
if (a == 1)
{
int param = 5;
return &param;
}
else if (a == 2)
{
double param = 5.5;
return &param;
}
else if (a == 3)
{
string param = "hello";
return &param;
}
else
{
return nullptr;
}
}
int main()
{
void *ptr = func(3);//
cout << ptr;// print the address not the value
getchar();
return 0;
}
param is an automatic variable. You cannot return it and use it outside its scope.
param exists only within func, if you return it, the result is Undefined Behaviour.
To fix it you can either:
allocate param on the heap dynamically. After you do that, you can safely return param address but you have to remember to free it when you don't need it.
Here is correction of your code
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
void * func(int a)
{
if (a == 1)
{
int *param = new int(5);
return param;
}
else if (a == 2)
{
double *param = new double(5.5);
return param;
}
else if (a == 3)
{
char *param = new char[50];
strcpy(param, "test");
return param;
}
return nullptr;
}
int main()
{
int *ptr = (int*)func(1);
cout << *ptr << std::endl; // print the int value
delete ptr;
double *ptr2 = (double*)func(2);
cout << *ptr2 << std::endl; // print the double value
delete ptr2;
char *ptr3 = (char*)func(3);
cout << ptr3 << std::endl; // print the string
delete[] ptr3;
getchar();
return 0;
}
If you can use C++17, you can easily solve it by using a std::variant instead of a void *:
#include<iostream>
#include<string>
#include<variant>
std::variant<int, double, std::string, void *> func(int a) {
if (a == 1) {
int param = 5;
return param;
} else if (a == 2) {
double param = 5.5;
return param;
} else if (a == 3) {
std::string param = "hello";
return param;
} else {
return nullptr;
}
}
int main() {
std::visit([](auto v) {
std::cout << v << std::endl;
}, func(3));
}
See it up and running on wandbox.
In C++11/14 you can do the same with a tagged union. The basic idea is that what you return contains enough information so that the caller can get out of it the original type.
Alternatives exist.
As an example, you could erase the type and return a pair that contains both the original (erased) variable and a pointer to function filled with an instantiation of a function template. The latter will be able to reconstruct the original variable from a void * for it knows its type.
Well, pretty much a great machinery you can avoid to use with a tagged union or a std::variant (more or less a type-safe version of a tagged union at the end of the day).
What you're returning is the address of a local variable. That variable goes out of scope when the function returns, meaning that the memory it was using could be reused. Attempting to dereference that pointer (i.e. access the memory it points to) invokes undefined behavior.
Even if you were returning a valid pointer, the fact that your function returns a void * means that any type information regarding what that pointer was pointing to is lost. You could print one or more bytes starting at that address, but it won't tell you what the original type was.
Even if that pointer were valid, you simply can't have enough information to force safely a cast to something and then print it.
No information of its size, no information of its internal layout. So,you simply can not print what's pointed by a void*, unless you have some information prepared by hand somewhere, and force a static_cast to the known type.
For example:
double x = 1.2;
int y = 5;
int f(void** output) {
static int x;
if ( x++ ) {
*output = &x;
return 1;
}
*output = &y;
return 2;
}
...
void* out;
int r = f(&out);
if ( r == 1 ) cout << *(static_cast<double*>(out));
else if ( r == 2 ) cout << *(static_cast<int*>(out));

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.

C++ Dynamically Define Function

I am on visual c++ working on a console calculator, I am creating a way to let the user define a custom linear function. Here is where I am stumped: Once I get the users desired name of the function, the slope, and the y-intercept, I need to use that data to create a callable function that I can pass to muParser.
In muParser, you define custom functions like this:
double func(double x)
{
return 5*x + 7; // return m*x + b;
}
MyParser.DefineFun("f", func);
MyParser.SetExpr("f(9.5) - pi");
double dResult = MyParser.Eval();
How could I dynamically create a function like this based on the users input for the values 'm' and 'b' and pass that to the 'DefineFun()' method?
This is what I have so far:
void cb_SetFunc(void)
{
string FuncName, sM, sB;
double dM, dB;
bool GettingName = true;
bool GettingM = true;
bool GettingB = true;
regex NumPattern("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?");
EchoLn(">>> First, enter the functions name. (Enter 'cancel' to abort)");
EchoLn(">>> Only letters, numbers, and underscores can be used.");
try
{
do // Get the function name
{
Echo(">>> Enter name: ");
FuncName = GetLn();
if (UserCanceled(FuncName)) return;
if (!ValidVarName(FuncName))
{
EchoLn(">>> Please only use letters, numbers, and underscores.");
continue;
}
GettingName = false;
} while (GettingName);
do // Get the function slope
{
Echo(">>> Enter slope (m): ");
sM = GetLn();
if (UserCanceled(sM)) return;
if (!regex_match(sM, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dM = atof(sM.c_str());
GettingM = false;
} while (GettingM);
do // Get the function y-intercept
{
Echo(">>> Enter y-intercept (b): ");
sB = GetLn();
if (UserCanceled(sB)) return;
if (!regex_match(sB, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dB = atof(sB.c_str());
GettingB = false;
} while (GettingB);
// ------------
// TODO: Create function from dM (slope) and
// dB (y-intercept) and pass to 'DefineFun()'
// ------------
}
catch (...)
{
ErrMsg("An unexpected error occured while trying to set the function.");
}
}
I was thinking that there isn't a way to define an individual method for each user-defined-function. Would I need to make a vector<pair<double, double>> FuncArgs; to keep track of the appropriate slopes and y-intercepts then call them dynamically from the function? How would I specify which pair to use when I pass it to DefineFun(FuncStrName, FuncMethod)?
What you need (in addition to a script language interpreter) is called a "trampoline". There is no standard solution to create those, in particular since it involves creating code at runtime.
Of course, if you accept a fixed number of trampolines, you can create them at compile time. And if they're all linear, this might be even easier:
const int N = 20; // Arbitrary
int m[N] = { 0 };
int b[N] = { 0 };
template<int I> double f(double x) { return m[I] * x + b; }
This defines a set of 20 functions f<0>...f<19> which use m[0]...m[19] respectively.
Edit:
// Helper class template to instantiate all trampoline functions.
double (*fptr_array[N])(double) = { 0 };
template<int I> struct init_fptr<int I> {
static const double (*fptr)(double) = fptr_array[I] = &f<I>;
typedef init_fptr<I-1> recurse;
};
template<> struct init_fptr<-1> { };
I would keep it simple:
#include <functional>
std::function<double(double)> f; // this is your dynamic function
int slope, yintercept; // populate from user input
f = [=](double x) -> double { return slope * x + yintercept; };
Now you can pass the object f to your parser, which can then call f(x) at its own leisure. The function object packages the captured values of slope and yintercept.
GiNaC is C++ lib which can parse and evaluate math expressions.
Generating a fixed array of functions bindable to boost function.
Someone else already said about a similar method, but since I'd taken the time to write the code, here it is anyway.
#include <boost/function.hpp>
enum {
MAX_FUNC_SLOTS = 255
};
struct FuncSlot
{
double (*f_)(double);
boost::function<double(double)> closure_;
};
FuncSlot s_func_slots_[MAX_FUNC_SLOTS];
template <int Slot>
struct FuncSlotFunc
{
static void init() {
FuncSlotFunc<Slot-1>::init();
s_func_slots_[Slot - 1].f_ = &FuncSlotFunc<Slot>::call;
}
static double call(double v) {
return s_func_slots_[Slot - 1].closure_(v);
}
};
template <> struct FuncSlotFunc<0> {
static void init() {}
};
struct LinearTransform
{
double m_;
double c_;
LinearTransform(double m, double c)
: m_(m)
, c_(c)
{}
double operator()(double v) const {
return (v * m_) + c_;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
FuncSlotFunc<MAX_FUNC_SLOTS>::init();
s_func_slots_[0].closure_ = LinearTransform(1, 0);
s_func_slots_[1].closure_ = LinearTransform(5, 1);
std::cout << s_func_slots_[0].f_(1.0) << std::endl; // should print 1
std::cout << s_func_slots_[1].f_(1.0) << std::endl; // should print 6
system("pause");
return 0;
}
So, you can get the function pointer with: s_func_slots_[xxx].f_
And set your action with s_func_slots_[xxx].closure_
Try to embed to your application some script language. Years ago I was using Tcl for similar purpose - but I do not know what is the current time best choice.
Either you can start from Tcl or search yourself for something better:
See: Adding Tcl/Tk to a C application