Array of pointer-to-functions

Discussion in 'C++' started by I, Sep 17, 2012.

1. IGuest

Hello,

Question: How do I create a n array of pointer - to - functions to be filled by a user?
My goal is to create the calculate function, which takes two values and passes them to a array of pointer-to-functions, which calculates something from those 2 values and returns it.

I am not getting any build errors. It is definitly not running though.

I am guessing my problem is in one of 3 places:
1.) the calculate protoype
2.) the calculate function
3.) the defenition of double calculate(double y, double x, int z,double (*pt[])(double a,double b))
but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.

Thanks
I

Here is my code:

#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cmath>
#include <limits>

using namespace std;
//int size;
//functions below here
double calculate(double y, double x, int z,double (*pt[])(double a,double b)); //changed 4 to [] in hopes of creating a blank array
double subtract(double a, double b);
double mult(double a, double b);
double divide(double a, double b);
double mean(double a, double b);
double pythag(double a, double b);
/*
* begin main
*/
int main()
{
int choice,size_choice;
double a,b,test;
cout<<"Enter two values: \n";
if(!(cin>>a>>b))
cout<<"Catastrophic Error!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
//Now going to attempt to write a switch that allow users to choose up to 5 functions to operate on their numbers
cout<<"Choose the # of functions you wish to use (only six functions currently available) \n";
while(1)
{
if(!(cin>>size_choice))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout<<"Failure\n";
}
else
break;
}
"1.) add 2.) subtract 3.) mult\n"
"4.) divide 5.) mean 6.) pythag\n";
//cin>>choice;
for(int i=0;i<size_choice;i++)
{
cin>>choice;
switch(choice)
{
break;
case 2: pt=subtract;
break;
case 3: pt=mult;
break;
case 4: pt=divide;
break;
case 5: pt=mean;
break;
case 6: pt=pythag;
break;
}
}
calculate(a,b,size_choice,pt);
return 0;
}
/*
*/
double calculate(double y, double x,int z, double (*pt[])(double,double))
{
double * temp = new double [z];
//double a,b,test=0;
for(int i=0;i<z;i++)
{
temp=(*pt)(x,y);
cout<<temp<<" next \n";
}

delete [] temp;
}
{
return a+b;
}
double subtract(double a, double b)
{
double total=a-b;
}
double mult(double a, double b)
{
return a*b;
}
double divide(double a, double b)
{

double total=a/b;
//double remainder=a%b;
}
double mean(double a, double b)
{
return (a+b)/2;
}
double pythag(double a, double b)
{
return sqrt((a*a)+(b*b));
}

I, Sep 17, 2012

2. Guest

On Sunday, September 16, 2012 6:25:52 PM UTC-5, I wrote:
> Hello,
>
>
>
> Question: How do I create a n array of pointer - to - functions to be filled by a user?
>
> My goal is to create the calculate function, which takes two values and passes them to a array of pointer-to-functions, which calculates something from those 2 values and returns it.
>
>
>
> I am not getting any build errors. It is definitly not running though.
>
>
>
> I am guessing my problem is in one of 3 places:
>
> 1.) the calculate protoype
>
> 2.) the calculate function
>
> 3.) the defenition of double calculate(double y, double x, int z,double (*pt[])(double a,double b))
>
> but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.
>
>
>
> Thanks
>
> I
>
>
>
> Here is my code:
>
>
>
> #include <cstdlib>
>
> #include <iostream>
>
> #include <cstring>
>
> #include <cmath>
>
> #include <limits>
>
>
>
> using namespace std;
>
> //int size;
>
> //functions below here
>
> double calculate(double y, double x, int z,double (*pt[])(double a,doubleb)); //changed 4 to [] in hopes of creating a blank array
>
> double add(double a, double b);
>
> double subtract(double a, double b);
>
> double mult(double a, double b);
>
> double divide(double a, double b);
>
> double mean(double a, double b);
>
> double pythag(double a, double b);
>
> /*
>
> * begin main
>
> */
>
> int main()
>
> {
>
> int choice,size_choice;
>
> double (*pt[size_choice])(double a, double b);//={add,subtract,mult,divide};

The problem is here. This is not valid (the size of an array must be a constant), although some compilers accept it. But even with those compilers that accept it, it won't do what you want because size_choice hasn't been initialized. Most likely it will contain a random large value, and the program will try to allocate a large amount of memory on the stack, causing a stackoverflow.

> double a,b,test;
>
> cout<<"Enter two values: \n";
>
> if(!(cin>>a>>b))
>
> cout<<"Catastrophic Error!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
>
> //Now going to attempt to write a switch that allow users to choose up to 5 functions to operate on their numbers
>
> cout<<"Choose the # of functions you wish to use (only six functions currently available) \n";
>
> while(1)
>
> {
>
> if(!(cin>>size_choice))
>
> {
>
> cin.clear();
>
> cin.ignore(numeric_limits<streamsize>::max(),'\n');
>
> cout<<"Failure\n";
>
> }
>
> else
>
> break;
>
> }

Here is where you would declare the array, now that size_choice has been initialized:

double (*pt[size_choice])(double a, double b);// {add, subtract, mult, divide};

Or use std::vector:

vector<double(*)(double, double)> pt(size_choice);

But I don't see why you need to allocate only size_choice pointers. Just declare an array that contains all the function pointers and use only the ones you need.

>
> "1.) add 2.) subtract 3.) mult\n"
>
> "4.) divide 5.) mean 6.) pythag\n";
>
> //cin>>choice;
>
> for(int i=0;i<size_choice;i++)
>
> {
>
> cin>>choice;
>
> switch(choice)
>
> {
>
>
> break;
>
> case 2: pt=subtract;
>
> break;
>
> case 3: pt=mult;
>
> break;
>
> case 4: pt=divide;
>
> break;
>
> case 5: pt=mean;
>
> break;
>
> case 6: pt=pythag;
>
> break;
>
> }
>
> }
>
> calculate(a,b,size_choice,pt);
>
> return 0;
>
> }
>
> /*
>
> *Define your functions after break!
>
> */
>
> double calculate(double y, double x,int z, double (*pt[])(double,double))
>
> {
>
> double * temp = new double [z];
>
> //double a,b,test=0;
>
> for(int i=0;i<z;i++)
>
> {
>
> temp=(*pt)(x,y);
>
> cout<<temp<<" next \n";
>
> }
>
>
>
> delete [] temp;
>
> }
>
> double add(double a, double b)
>
> {
>
> return a+b;
>
> }
>
> double subtract(double a, double b)
>
> {
>
> double total=a-b;
>
>
> }
>
> double mult(double a, double b)
>
> {
>
> return a*b;
>
> }
>
> double divide(double a, double b)
>
> {
>
>
>
> double total=a/b;
>
> //double remainder=a%b;
>
>
> }
>
> double mean(double a, double b)
>
> {
>
> return (a+b)/2;
>
> }
>
> double pythag(double a, double b)
>
> {
>
> return sqrt((a*a)+(b*b));
>
> }

By the way, a better way to do this is with polymorphism:

class Operation
{
public:
virtual double Calculate(double a, double b) = 0;
};

{
public:
double Calculate(double a, double b) { return a + b; }
};

class SubtractOperation : public Operation
{
public:
double Calculate(double a, double b) { return a - b; }
};

....

Then create a vector of Operations:

vector<Operation*> operations(size_choice);

And add objects to it like you added function pointers to the other array:

switch (choice)
{
case 1:
break;
case 2:
operations = new SubtractOperation();
break;
....
}

And then call Calculate on all the objects:

for (int i = 0; i < n; ++i)
cout << operations->Calculate(a, b) << endl;

, Sep 17, 2012

3. IGuest

On Sunday, September 16, 2012 10:11:33 PM UTC-5, (unknown) wrote:
> On Sunday, September 16, 2012 6:25:52 PM UTC-5, I wrote:
>
> > Hello,

>
> >

>
> >

>
> >

>
> > Question: How do I create a n array of pointer - to - functions to be filled by a user?

>
> >

>
> > My goal is to create the calculate function, which takes two values andpasses them to a array of pointer-to-functions, which calculates somethingfrom those 2 values and returns it.

>
> >

>
> >

>
> >

>
> > I am not getting any build errors. It is definitly not running though.

>
> >

>
> >

>
> >

>
> > I am guessing my problem is in one of 3 places:

>
> >

>
> > 1.) the calculate protoype

>
> >

>
> > 2.) the calculate function

>
> >

>
> > 3.) the defenition of double calculate(double y, double x, int z,double(*pt[])(double a,double b))

>
> >

>
> > but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.

>
> >

>
> >

>
> >

>
> > Thanks

>
> >

>
> > I

>
> >

>
> >

>
> >

>
> > Here is my code:

>
> >

>
> >

>
> >

>
> > #include <cstdlib>

>
> >

>
> > #include <iostream>

>
> >

>
> > #include <cstring>

>
> >

>
> > #include <cmath>

>
> >

>
> > #include <limits>

>
> >

>
> >

>
> >

>
> > using namespace std;

>
> >

>
> > //int size;

>
> >

>
> > //functions below here

>
> >

>
> > double calculate(double y, double x, int z,double (*pt[])(double a,double b)); //changed 4 to [] in hopes of creating a blank array

>
> >

>
> > double add(double a, double b);

>
> >

>
> > double subtract(double a, double b);

>
> >

>
> > double mult(double a, double b);

>
> >

>
> > double divide(double a, double b);

>
> >

>
> > double mean(double a, double b);

>
> >

>
> > double pythag(double a, double b);

>
> >

>
> > /*

>
> >

>
> > * begin main

>
> >

>
> > */

>
> >

>
> > int main()

>
> >

>
> > {

>
> >

>
> > int choice,size_choice;

>
> >

>
> > double (*pt[size_choice])(double a, double b);//={add,subtract,mult,divide};

>
>
>
> The problem is here. This is not valid (the size of an array must be a constant), although some compilers accept it. But even with those compilers that accept it, it won't do what you want because size_choice hasn't been initialized. Most likely it will contain a random large value, and the program will try to allocate a large amount of memory on the stack, causing a stack overflow.
>
>
>
> > double a,b,test;

>
> >

>
> > cout<<"Enter two values: \n";

>
> >

>
> > if(!(cin>>a>>b))

>
> >

>
> > cout<<"Catastrophic Error!!!!!!!!!!!!!!!!!!!!!!!!!!\n";

>
> >

>
> > //Now going to attempt to write a switch that allow users to chooseup to 5 functions to operate on their numbers

>
> >

>
> > cout<<"Choose the # of functions you wish to use (only six functions currently available) \n";

>
> >

>
> > while(1)

>
> >

>
> > {

>
> >

>
> > if(!(cin>>size_choice))

>
> >

>
> > {

>
> >

>
> > cin.clear();

>
> >

>
> > cin.ignore(numeric_limits<streamsize>::max(),'\n');

>
> >

>
> > cout<<"Failure\n";

>
> >

>
> > }

>
> >

>
> > else

>
> >

>
> > break;

>
> >

>
> > }

>
>
>
> Here is where you would declare the array, now that size_choice has been initialized:
>
>
>
> double (*pt[size_choice])(double a, double b);// {add, subtract, mult, divide};
>
>
>
> Or use std::vector:
>
>
>
> vector<double(*)(double, double)> pt(size_choice);
>
>
>
> But I don't see why you need to allocate only size_choice pointers. Just declare an array that contains all the function pointers and use only the ones you need.
>
>
>
> > cout<<"Choose your functions: \n"

>
> >

>
> > "1.) add 2.) subtract 3.) mult\n"

>
> >

>
> > "4.) divide 5.) mean 6.) pythag\n";

>
> >

>
> > //cin>>choice;

>
> >

>
> > for(int i=0;i<size_choice;i++)

>
> >

>
> > {

>
> >

>
> > cin>>choice;

>
> >

>
> > switch(choice)

>
> >

>
> > {

>
> >

>

>
> >

>
> > break;

>
> >

>
> > case 2: pt=subtract;

>
> >

>
> > break;

>
> >

>
> > case 3: pt=mult;

>
> >

>
> > break;

>
> >

>
> > case 4: pt=divide;

>
> >

>
> > break;

>
> >

>
> > case 5: pt=mean;

>
> >

>
> > break;

>
> >

>
> > case 6: pt=pythag;

>
> >

>
> > break;

>
> >

>
> > }

>
> >

>
> > }

>
> >

>
> > calculate(a,b,size_choice,pt);

>
> >

>
> > return 0;

>
> >

>
> > }

>
> >

>
> > /*

>
> >

>
> > *Define your functions after break!

>
> >

>
> > */

>
> >

>
> > double calculate(double y, double x,int z, double (*pt[])(double,double))

>
> >

>
> > {

>
> >

>
> > double * temp = new double [z];

>
> >

>
> > //double a,b,test=0;

>
> >

>
> > for(int i=0;i<z;i++)

>
> >

>
> > {

>
> >

>
> > temp=(*pt)(x,y);

>
> >

>
> > cout<<temp<<" next \n";

>
> >

>
> > }

>
> >

>
> >

>
> >

>
> > delete [] temp;

>
> >

>
> > }

>
> >

>
> > double add(double a, double b)

>
> >

>
> > {

>
> >

>
> > return a+b;

>
> >

>
> > }

>
> >

>
> > double subtract(double a, double b)

>
> >

>
> > {

>
> >

>
> > double total=a-b;

>
> >

>

>
> >

>
> > }

>
> >

>
> > double mult(double a, double b)

>
> >

>
> > {

>
> >

>
> > return a*b;

>
> >

>
> > }

>
> >

>
> > double divide(double a, double b)

>
> >

>
> > {

>
> >

>
> >

>
> >

>
> > double total=a/b;

>
> >

>
> > //double remainder=a%b;

>
> >

>

>
> >

>
> > }

>
> >

>
> > double mean(double a, double b)

>
> >

>
> > {

>
> >

>
> > return (a+b)/2;

>
> >

>
> > }

>
> >

>
> > double pythag(double a, double b)

>
> >

>
> > {

>
> >

>
> > return sqrt((a*a)+(b*b));

>
> >

>
> > }

>
>
>
> By the way, a better way to do this is with polymorphism:
>
>
>
> class Operation
>
> {
>
> public:
>
> virtual double Calculate(double a, double b) = 0;
>
> };
>
>
>
> class AddOperation : public Operation
>
> {
>
> public:
>
> double Calculate(double a, double b) { return a + b; }
>
> };
>
>
>
> class SubtractOperation : public Operation
>
> {
>
> public:
>
> double Calculate(double a, double b) { return a - b; }
>
> };
>
>
>
> ...
>
>
>
> Then create a vector of Operations:
>
>
>
> vector<Operation*> operations(size_choice);
>
>
>
> And add objects to it like you added function pointers to the other array:
>
>
>
> switch (choice)
>
> {
>
> case 1:
>
>
> break;
>
> case 2:
>
> operations = new SubtractOperation();
>
> break;
>
> ...
>
> }
>
>
>
> And then call Calculate on all the objects:
>
>
>
> for (int i = 0; i < n; ++i)
>
> cout << operations->Calculate(a, b) << endl;

On Sunday, September 16, 2012 10:11:33 PM UTC-5, (unknown) wrote:
> On Sunday, September 16, 2012 6:25:52 PM UTC-5, I wrote:
>
> > Hello,

>
> >

>
> >

>
> >

>
> > Question: How do I create a n array of pointer - to - functions to be filled by a user?

>
> >

>
> > My goal is to create the calculate function, which takes two values andpasses them to a array of pointer-to-functions, which calculates somethingfrom those 2 values and returns it.

>
> >

>
> >

>
> >

>
> > I am not getting any build errors. It is definitly not running though.

>
> >

>
> >

>
> >

>
> > I am guessing my problem is in one of 3 places:

>
> >

>
> > 1.) the calculate protoype

>
> >

>
> > 2.) the calculate function

>
> >

>
> > 3.) the defenition of double calculate(double y, double x, int z,double(*pt[])(double a,double b))

>
> >

>
> > but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.

>
> >

>
> >

>
> >

>
> > Thanks

>
> >

>
> > I

>
> >

>
> >

>
> >

>
> > Here is my code:

>
> >

>
> >

>
> >

>
> > #include <cstdlib>

>
> >

>
> > #include <iostream>

>
> >

>
> > #include <cstring>

>
> >

>
> > #include <cmath>

>
> >

>
> > #include <limits>

>
> >

>
> >

>
> >

>
> > using namespace std;

>
> >

>
> > //int size;

>
> >

>
> > //functions below here

>
> >

>
> > double calculate(double y, double x, int z,double (*pt[])(double a,double b)); //changed 4 to [] in hopes of creating a blank array

>
> >

>
> > double add(double a, double b);

>
> >

>
> > double subtract(double a, double b);

>
> >

>
> > double mult(double a, double b);

>
> >

>
> > double divide(double a, double b);

>
> >

>
> > double mean(double a, double b);

>
> >

>
> > double pythag(double a, double b);

>
> >

>
> > /*

>
> >

>
> > * begin main

>
> >

>
> > */

>
> >

>
> > int main()

>
> >

>
> > {

>
> >

>
> > int choice,size_choice;

>
> >

>
> > double (*pt[size_choice])(double a, double b);//={add,subtract,mult,divide};

>
>
>
> The problem is here. This is not valid (the size of an array must be a constant), although some compilers accept it. But even with those compilers that accept it, it won't do what you want because size_choice hasn't been initialized. Most likely it will contain a random large value, and the program will try to allocate a large amount of memory on the stack, causing a stack overflow.
>
>
>
> > double a,b,test;

>
> >

>
> > cout<<"Enter two values: \n";

>
> >

>
> > if(!(cin>>a>>b))

>
> >

>
> > cout<<"Catastrophic Error!!!!!!!!!!!!!!!!!!!!!!!!!!\n";

>
> >

>
> > //Now going to attempt to write a switch that allow users to chooseup to 5 functions to operate on their numbers

>
> >

>
> > cout<<"Choose the # of functions you wish to use (only six functions currently available) \n";

>
> >

>
> > while(1)

>
> >

>
> > {

>
> >

>
> > if(!(cin>>size_choice))

>
> >

>
> > {

>
> >

>
> > cin.clear();

>
> >

>
> > cin.ignore(numeric_limits<streamsize>::max(),'\n');

>
> >

>
> > cout<<"Failure\n";

>
> >

>
> > }

>
> >

>
> > else

>
> >

>
> > break;

>
> >

>
> > }

>
>
>
> Here is where you would declare the array, now that size_choice has been initialized:
>
>
>
> double (*pt[size_choice])(double a, double b);// {add, subtract, mult, divide};
>
>
>
> Or use std::vector:
>
>
>
> vector<double(*)(double, double)> pt(size_choice);
>
>
>
> But I don't see why you need to allocate only size_choice pointers. Just declare an array that contains all the function pointers and use only the ones you need.
>
>
>
> > cout<<"Choose your functions: \n"

>
> >

>
> > "1.) add 2.) subtract 3.) mult\n"

>
> >

>
> > "4.) divide 5.) mean 6.) pythag\n";

>
> >

>
> > //cin>>choice;

>
> >

>
> > for(int i=0;i<size_choice;i++)

>
> >

>
> > {

>
> >

>
> > cin>>choice;

>
> >

>
> > switch(choice)

>
> >

>
> > {

>
> >

>

>
> >

>
> > break;

>
> >

>
> > case 2: pt=subtract;

>
> >

>
> > break;

>
> >

>
> > case 3: pt=mult;

>
> >

>
> > break;

>
> >

>
> > case 4: pt=divide;

>
> >

>
> > break;

>
> >

>
> > case 5: pt=mean;

>
> >

>
> > break;

>
> >

>
> > case 6: pt=pythag;

>
> >

>
> > break;

>
> >

>
> > }

>
> >

>
> > }

>
> >

>
> > calculate(a,b,size_choice,pt);

>
> >

>
> > return 0;

>
> >

>
> > }

>
> >

>
> > /*

>
> >

>
> > *Define your functions after break!

>
> >

>
> > */

>
> >

>
> > double calculate(double y, double x,int z, double (*pt[])(double,double))

>
> >

>
> > {

>
> >

>
> > double * temp = new double [z];

>
> >

>
> > //double a,b,test=0;

>
> >

>
> > for(int i=0;i<z;i++)

>
> >

>
> > {

>
> >

>
> > temp[i]=(*pt[i])(x,y);[/i][/i]
[i]
> [color=green]
> > [/color]
> [color=green]
> > cout<<temp[i]<<" next \n";[/i][/color][i]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > [/color]
> [color=green]
> > [/color]
> [color=green]
> > delete [] temp;[/color]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double add(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > return a+b;[/color]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double subtract(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > double total=a-b;[/color]
> [color=green]
> > [/color]
> [color=green]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double mult(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > return a*b;[/color]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double divide(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > [/color]
> [color=green]
> > [/color]
> [color=green]
> > double total=a/b;[/color]
> [color=green]
> > [/color]
> [color=green]
> > //double remainder=a%b;[/color]
> [color=green]
> > [/color]
> [color=green]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double mean(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > return (a+b)/2;[/color]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
> [color=green]
> > [/color]
> [color=green]
> > double pythag(double a, double b)[/color]
> [color=green]
> > [/color]
> [color=green]
> > {[/color]
> [color=green]
> > [/color]
> [color=green]
> > return sqrt((a*a)+(b*b));[/color]
> [color=green]
> > [/color]
> [color=green]
> > }[/color]
>
>
>
> By the way, a better way to do this is with polymorphism:
>
>
>
> class Operation
>
> {
>
> public:
>
> virtual double Calculate(double a, double b) = 0;
>
> };
>
>
>
> class AddOperation : public Operation
>
> {
>
> public:
>
> double Calculate(double a, double b) { return a + b; }
>
> };
>
>
>
> class SubtractOperation : public Operation
>
> {
>
> public:
>
> double Calculate(double a, double b) { return a - b; }
>
> };
>
>
>
> ...
>
>
>
> Then create a vector of Operations:
>
>
>
> vector<Operation*> operations(size_choice);
>
>
>
> And add objects to it like you added function pointers to the other array:
>
>
>
> switch (choice)
>
> {
>
> case 1:
>
>
> break;
>
> case 2:
>
> operations[i] = new SubtractOperation();
>
> break;
>
> ...
>
> }
>
>
>
> And then call Calculate on all the objects:
>
>
>
> for (int i = 0; i < n; ++i)
>
> cout << operations[i]->Calculate(a, b) << endl;[/i][/i][/i][/i][/i]
[i][i][i][i]

Great, thanks for the tip! Just getting into classes, hopefully polymorphisms will come up in the text.[/i][/i][/i][/i]

I, Sep 17, 2012
4. Guest

On Sunday, September 16, 2012 10:57:08 PM UTC-5, I wrote:
> Great, thanks for the tip! Just getting into classes, hopefully polymorphisms will come up in the text.

More generally, don't declare all variables at the top of a function. Declare them right where they are used. This is not just about correctness (like in this case), but also about readability and style.

, Sep 17, 2012
5. WernerGuest

On Monday, September 17, 2012 1:25:52 AM UTC+2, I wrote:
> Hello,
>
>
>
> Question: How do I create a n array of pointer - to - functions to be filled by a user?

that would be (for C++11):

std::vector<void(*)(double,double)> functions =
{
add, subtract, mult, divide, mean, pythag
};

or

void (*farray[]) (double, double) =
{
add, subtract, mult, divide, mean, pythag
};

if( choice < farray.size() )
{
calculate (...farray[choice] );
}

Why the switch statement?

Kind regards,

Werner

Werner, Sep 17, 2012
6. Luca RisoliaGuest

On 17/09/2012 01:25, I wrote:
> I am not getting any build errors. It is definitly not running though.

That's probably because there is one bug in your code at least (see below).

> 3.) the defenition of double calculate(double y, double x, int z,double (*pt[])(double a,double b))
> but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.

> Here is my code:

> int main()
> {
> int choice,size_choice;

size_choice is uninitialized there. It may hold a non-positive value.

> double (*pt[size_choice])(double a, double b);//={add,subtract,mult,divide};

When size_choice is <= 0, the above statement leads to Undefined Behaviour.

Luca Risolia, Sep 17, 2012
7. IGuest

> Why the switch statement?
>
>
>
> Kind regards,
>
>
>
> Werner

I took a problem from C++ Primer Plus and tried to up the degree of difficulty, The original goal was to use a pointer to function to some function like add(). I wanted to see if I could set up a situation that would allow a user to select multiple functions of their choosing. Switch is the best wayI currently know.

Ian

I, Sep 17, 2012
8. IGuest

On Monday, September 17, 2012 9:27:14 AM UTC-5, Luca Risolia wrote:
> On 17/09/2012 01:25, I wrote:
>
> > I am not getting any build errors. It is definitly not running though.

>
>
>
> That's probably because there is one bug in your code at least (see below).
>
>
>
> > 3.) the defenition of double calculate(double y, double x, int z,double (*pt[])(double a,double b))

>
> > but I am running out of ideas (and still find pointers confusing). Any hints would be welcome and appreciated.

>
>
>
> > Here is my code:

>
>
>
> > int main()

>
> > {

>
> > int choice,size_choice;

>
>
>
> size_choice is uninitialized there. It may hold a non-positive value.
>
>
>
> > double (*pt[size_choice])(double a, double b);//={add,subtract,mult,divide};

>
>
>
> When size_choice is <= 0, the above statement leads to Undefined Behaviour.

As soon as I moved double (*pt[size_choice])(double a, double b) below size_choice initialization it worked fine. Thanks!

I, Sep 17, 2012
9. Guest

On Monday, September 17, 2012 8:57:00 AM UTC-5, Scott Lurndal wrote:
> writes:
>
> >On Sunday, September 16, 2012 10:57:08 PM UTC-5, I wrote:

>
> >> Great, thanks for the tip! Just getting into classes, hopefully polymorphisms will come up in the text.

>
> >

>
> >More generally, don't declare all variables at the top of a function. Declare them right where they are used. This is not just about correctness (like in this case), but also about readability and style.

>
>
>
>
>
> Which is a matter of opinion. I prefer all variables to be declared at the beginning of a basic-block. Makes it
>
> easier to find when functions get larger than a handful of lines. Also prevents compile errors in the presence
>
> of goto's (which can be used safely and properly, primarily as early exits w/cleanup).

What use is "finding" a variable, when you don't know how it will be used? Declaring variables too far from where they are used makes you jump back and forth trying to see where it's declared and where it's actually used.

There are other points, and this is actually a FAQ: http://www.parashift.com/c++-faq-lite/declare-near-first-use.html

, Sep 17, 2012
10. Ian CollinsGuest

On 09/18/12 01:57 AM, Scott Lurndal wrote:
> writes:
>> On Sunday, September 16, 2012 10:57:08 PM UTC-5, I wrote:
>>> Great, thanks for the tip! Just getting into classes, hopefully polymorphisms will come up in the text.

>>
>> More generally, don't declare all variables at the top of a function. Declare them right where they are used. This is not just about correctness (like in this case), but also about readability and style.

>
>
> Which is a matter of opinion. I prefer all variables to be declared at the beginning of a basic-block. Makes it
> easier to find when functions get larger than a handful of lines. Also prevents compile errors in the presence
> of goto's (which can be used safely and properly, primarily as early exits w/cleanup).

I smell Troll bait

We all know functions shouldn't be longer than a handful of lines and no
C++ programmer would ever risk his or her head by using goto.

--
Ian Collins

Ian Collins, Sep 17, 2012
11. Ian CollinsGuest

On 09/18/12 11:27 AM, Scott Lurndal wrote:
> Ian Collins<> writes:
>> On 09/18/12 01:57 AM, Scott Lurndal wrote:
>>> writes:
>>>> On Sunday, September 16, 2012 10:57:08 PM UTC-5, I wrote:
>>>>> Great, thanks for the tip! Just getting into classes, hopefully polymorphisms will come up in the text.
>>>>
>>>> More generally, don't declare all variables at the top of a function. Declare them right where they are used. This is not just about correctness (like in this case), but also about readability and style.
>>>
>>>
>>> Which is a matter of opinion. I prefer all variables to be declared at the beginning of a basic-block. Makes it
>>> easier to find when functions get larger than a handful of lines. Also prevents compile errors in the presence
>>> of goto's (which can be used safely and properly, primarily as early exits w/cleanup).

>>
>> I smell Troll bait
>>
>> We all know functions shouldn't be longer than a handful of lines and no
>> C++ programmer would ever risk his or her head by using goto.

>
> Well, after a microkernel, two hypervisors, two computer simulators and three operating systems
> all written in C++, I've seen some pretty long functions (the fork implementation,
> for example), and judicious use of goto is often warranted (and used - usually
> for function exits where resources must be returned on failure, e.g. locks unlocked,
> memory returned, et alia)[*].
>
> Given the similar characteristics of multithreaded applications, similar considerations
> apply.
>
>
> [*] While none of these projects used exceptions in any way, RAII techniques were
> used in a couple of the more complicated paths in 1991, specifically the fork implementation
> had a local class instance named tForkFailure whose destructor would clean up a
> partial fork when the fork function exited, but in most cases, a simple goto was
> sufficient to release a lock at function return (the complex nature of locking in
> a general purpose unix-compatible operating system precluded using RAII techniques
> to unlock the lock; occasionally the lock need be left locked on function exit).

Well that was 20 years ago and techniques and tools have moved on since
then. If you want a lock to stay locked, tell the object that manages
it not to release it when it gets destroyed.

The use of goto for clean up code is common enough in C, but I would be
very surprised to see it in current C++ and even more surprised to see a
valid justification for its use.

--
Ian Collins

Ian Collins, Sep 18, 2012
12. PavelGuest

Ian Collins wrote:
> On 09/18/12 11:27 AM, Scott Lurndal wrote:
>> Ian Collins<> writes:
>>> On 09/18/12 01:57 AM, Scott Lurndal wrote:
>>>> writes:
>>>>> On Sunday, September 16, 2012 10:57:08 PM UTC-5, I wrote:
>>>>>> Great, thanks for the tip! Just getting into classes, hopefully
>>>>>> polymorphisms will come up in the text.
>>>>>
>>>>> More generally, don't declare all variables at the top of a function.
>>>>> Declare them right where they are used. This is not just about correctness
>>>>
>>>>
>>>> Which is a matter of opinion. I prefer all variables to be declared at the
>>>> beginning of a basic-block. Makes it
>>>> easier to find when functions get larger than a handful of lines. Also
>>>> prevents compile errors in the presence
>>>> of goto's (which can be used safely and properly, primarily as early exits
>>>> w/cleanup).
>>>
>>> I smell Troll bait
>>>
>>> We all know functions shouldn't be longer than a handful of lines and no
>>> C++ programmer would ever risk his or her head by using goto.

>>
>> Well, after a microkernel, two hypervisors, two computer simulators and three
>> operating systems
>> all written in C++, I've seen some pretty long functions (the fork
>> implementation,
>> for example), and judicious use of goto is often warranted (and used - usually
>> for function exits where resources must be returned on failure, e.g. locks
>> unlocked,
>> memory returned, et alia)[*].
>>
>> Given the similar characteristics of multithreaded applications, similar
>> considerations
>> apply.
>>
>>
>> [*] While none of these projects used exceptions in any way, RAII techniques were
>> used in a couple of the more complicated paths in 1991, specifically the
>> fork implementation
>> had a local class instance named tForkFailure whose destructor would
>> clean up a
>> partial fork when the fork function exited, but in most cases, a simple
>> goto was
>> sufficient to release a lock at function return (the complex nature of
>> locking in
>> a general purpose unix-compatible operating system precluded using RAII
>> techniques
>> to unlock the lock; occasionally the lock need be left locked on function
>> exit).

>
> Well that was 20 years ago and techniques and tools have moved on since then.
> If you want a lock to stay locked, tell the object that manages it not to
> release it when it gets destroyed.
>
> The use of goto for clean up code is common enough in C, but I would be very
> surprised to see it in current C++ and even more surprised to see a valid
> justification for its use.
>

OSes and device drivers are still commonly written in C and other non-C++
languages. This was true 20 years ago and stays true now. Symbian (former
EPOC32) is the only one relatively successful one I am aware of that was written
in C++ -- but RAII part of its C++ was intentionally broken to allow manual
control of what's cleaned up and what's not and minimize overhead of the
exceptions (they did use exceptions.. of a kind, also not standard C++ -- but I

To summarize, now as 20 years ago, RAII (and C++) have yet to prove to be
competitive in device driver and kernel development.

(I am not saying this cannot be done; on the surface of things passing lock
ownership among scopes with the likes of unique_ptr seems at least doable; but I
am unaware of a convincing broadly known case-in-point; if you know any, I would
be eager to learn about it).

-Pavel

Pavel, Sep 18, 2012
13. Ian CollinsGuest

On 09/18/12 02:21 PM, Pavel wrote:
> Ian Collins wrote:
>>
>> The use of goto for clean up code is common enough in C, but I would be very
>> surprised to see it in current C++ and even more surprised to see a valid
>> justification for its use.
>>

> OSes and device drivers are still commonly written in C and other non-C++
> languages. This was true 20 years ago and stays true now. Symbian (former
> EPOC32) is the only one relatively successful one I am aware of that was written
> in C++ -- but RAII part of its C++ was intentionally broken to allow manual
> control of what's cleaned up and what's not and minimize overhead of the
> exceptions (they did use exceptions.. of a kind, also not standard C++ -- but I
>
> To summarize, now as 20 years ago, RAII (and C++) have yet to prove to be
> competitive in device driver and kernel development.
>
> (I am not saying this cannot be done; on the surface of things passing lock
> ownership among scopes with the likes of unique_ptr seems at least doable; but I
> am unaware of a convincing broadly known case-in-point; if you know any, I would
> be eager to learn about it).

The only examples I have are my own and embedded drivers I have worked on.

The two things holding C++ back in this area are prejudice from the C
programmers who maintain kernels and drivers and the lack of a common
C++ ABI.

--
Ian Collins

Ian Collins, Sep 18, 2012
14. Juha NieminenGuest

Scott Lurndal <> wrote:
> Well, after a microkernel, two hypervisors, two computer simulators and
> three operating systems all written in C++, I've seen some pretty long
> functions (the fork implementation, for example), and judicious use of
> goto is often warranted (and used - usually for function exits where
> resources must be returned on failure, e.g. locks unlocked, memory
> returned, et alia)[*].

Having programmed for about 10 years in C++ professionally (and longer
than that as a hobby), I don't remember having needed to use goto even
once.

And it's not like I religiously avoid it, and artificially try to shove
in contrived constructs that allow me to avoid writing "goto". The situations
just don't come up. I don't even remember having thought something like
"hmm, 'goto' would be the easiest solution here, how could I avoid it?"
There might have been one or two cases during my entire career that
something along those lines might have happened, but it has been really,
really rare.

Cleaning up resources with a 'goto' construct is particularly hideous
(and error-prone) in C++ both because it's not exception-safe, and
because there's a much, much better tool for exactly that: RAII.

Also, rarely does it happen that a function *must* be very large.
Usually you can split it into several functions, and more often than
not the resulting code will be easier to understand because of that.
(One exception that comes to mind is if you need a really large
switch block for some reason.)

Juha Nieminen, Sep 18, 2012
15. Juha NieminenGuest

Scott Lurndal <> wrote:
> Also prevents compile errors in the presence of goto's

You must be joking.

Juha Nieminen, Sep 18, 2012
16. Juha NieminenGuest

Pavel <> wrote:
> Symbian (former EPOC32) is the only one relatively successful one I am
> aware of that was written in C++ -- but RAII part of its C++ was
> intentionally broken to allow manual control of what's cleaned up and
> what's not and minimize overhead of the exceptions

That doesn't make much sense. It's not like RAII is non-deterministic
garbage collection where you have no control over when it's run. With
RAII you know *exactly* when the destructors will be called and in which
order (because the standard mandates so).

If you remove RAII from C++, you might just as well go back to C.

Juha Nieminen, Sep 18, 2012
17. Luca RisoliaGuest

On 18/09/2012 04:21, Pavel wrote:
> To summarize, now as 20 years ago, RAII (and C++) have yet to prove to
> be competitive in device driver and kernel development.

The Linux kernel is full of implementations of object-oriented design
patterns, for which C++ would be the only natural language.

Luca Risolia, Sep 18, 2012
18. WernerGuest

On Monday, September 17, 2012 6:10:34 PM UTC+2, I wrote:
> > Why the switch statement?

>
> >

>
> >

>
> >

>
> > Kind regards,

>
> >

>
> >

>
> >

>
> > Werner

>
>
>
> I took a problem from C++ Primer Plus and tried to up the degree of difficulty, The original goal was to use a pointer to function to some function like add(). I wanted to see if I could set up a situation that would allow a user to select multiple functions of their choosing. Switch is the best way I currently know.
>
>
>
> Ian

You already have an index into the array (or vector).

There is no need for a switch. The switch is redundant.

See below:

for(int i=0;i<size_choice;i++)
{
cin>>choice;

// Choice is already an index into the
// array of function pointers... Get it?
(*array_of_pointers[choice])(...);
}

Werner, Sep 18, 2012
19. Juha NieminenGuest

David Brown <> wrote:
> Please do not quote hundreds of lines just to add a single line comment!
> It is especially bad when you use Google's broken web interface to
> post - every quotation gets an extra blank line per "paragraph". And
> since every line of C code is a paragraph in this context, each re-quote
> doubles the number of blank lines messing up the post.

Do you wonder anymore why people top-post?

Juha Nieminen, Sep 18, 2012
20. Juha NieminenGuest

Scott Lurndal <> wrote:
>>If you remove RAII from C++, you might just as well go back to C.

>
> That's ridiculous. The class paradigm (data encapsulation) is enough
> of a benefit, without RAII, without templates, without exceptions, to
> make using C++ (or a subset thereof) useful for kernel development.

That would be such a crippled version of C++ that it would hardly be
worth using.

No generic data containers, no smart pointers, no automatic memory
management of any kind, inefficient pseudo-generic data containers and
algorithms (such as the horrid qsort()). In fact, for such objects to be
even slightly usable you would in practice have to limit the objects to be
dynamically allocated only, with no possibility of creating stack-based
objects, no copying objects, no handling them by value (because all those
require RAII to work properly).

(Yes, you could allow copying objects and handling them by value,
effectively making them C structs with support for member functions.
But without constructors, destructors and assignment operators, and
especially without being able to forbid them, it would be really
error-prone. Instantiate eg. a string "pseudo-object", inadvertently
assign it to another such object, and you have a problem.)

This would in fact be similar to Objective-C (which likewise has no RAII,
no constructors, no destructors, no assignment, cannot handle objects by
value, no templates), except that in Objective-C you at least have a
useful messaging system (which allows all kinds of neat stuff that isn't
possible even in full-fledged C++).

I don't see all that much difference between that crippled C++ and just C
(using structs and free-floating functions).

Juha Nieminen, Sep 18, 2012