0

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?

3
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by skatamatic
0

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?

0

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.

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.