Given the following function variables declarations in C++:

int (*f)(int);
int (*g)(int);
int (*h)(char);

when try to assign f=g its fine but trying to do h=g gives an error with a C++ compiler, can anyone tell me why this is?

Recommended Answers

All 4 Replies

The function arguments must be the same type. f and g take an int, while h takes a char.

The function arguments must be the same type. f and g take an int, while h takes a char.

Right, I see that they must be the same type, but what is the reason behind that. In other words does it complain because ints and chars are stored differently in memory?

Yes, they are stored differently. The sizeof(int) and sizeof(char) are not the same (on most machines). The c++ compiler (and standards) enforce parameter types and number of parameters. If you tried to pass an integer to a function that only expects a character it will have lots of problems because a (signed) character can only old values -126 to 127. See limits.h for exact range of values for each data type.

Ints usually take up 4 bytes of memory, while chars only take 1. You can always cast them into one another, but this can cause undesired results when converting from int to char - some bits may be truncated, or in some compilers could cause a conversion error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.