pointer to function error

I keep getting the error below when I try to pass a function pointer as a parameter in function fx1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>

int fx1(void(*p_funct)(int))
{
	(*p_funct)(10);
}

int fx2(int a)
{
	std::cout<<"FX2";
	a = a *a;
	std::cout<<a;
}

int main()
{
	int(*p_funct)(int); //make ptr
	p_funct = fx2;		//assign to a function
	fx1(p_funct);		//caller with pointer to function

	return 0;
}



 In function 'int main()':
..\src\main.cpp:19:13: error: invalid conversion from 'int (*)(int)' to 'void (*)(int)' [-fpermissive]
  fx1(p_funct);  //caller with pointer to function
1
2
3
int fx1(void(*p_funct)(int))

int(*p_funct)(int);
Last edited on
I'm sorry but I am not sure how to apply this.
1
2
3
4
5
6
7
8
9
10
11
/*
A pointer to a function that takes an int as a parameter
and returns nothing.
*/
int fx1(void(*p_funct)(int))

/*
A pointer to a function that takes an int as a parameter
and returns an int.
*/
int(*p_funct)(int);


Also fx1 and fx2 have no return value.
In fx1, you call the function like so:
 
(*p_funct)(10);

but in main, you call it like so:
 
fx1(p_funct);

Keep your style consistent. I would recommend that you call the function like you do in main. It looks cleaner and makes it more obvious what you are doing.
I would recommend that you call the function like you do in main.


I agree, I plan on cleaning it up. Thought exercise for now.

working program thx -

changed

int fx1(void(*p_funct)(int))
to:

int fx1(int(*p_funct)(int))



1
2
3
4
int fx1(int(*p_funct)(int))
{
	(*p_funct)(10);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>

int fx1(int(*p_funct)(int))
{
	(*p_funct)(10);
}

int fx2(int a)
{
	std::cout<<"FX2"<<std::endl;
	a = a *a;
	std::cout<<a;
	return a;
}

int main()
{
	int(*p_funct)(int); //make ptr
	p_funct = fx2;		//assign to a function
	fx1(p_funct);		//caller with pointer to function

	return 0;
}
Last edited on
1
2
3
4
int fx1(int(*p_funct)(int))
{
	(*p_funct)(10);
}


is more commonly written as (with the correction to actually return what it's promising to return):

1
2
3
4
int fx1(int(*p_funct)(int))
{
	return p_funct(10);
}
Topic archived. No new replies allowed.