Can somebody explain me the difference between the following?
- Those two
float *pointer[10];
float *(pointer[10]);
- and those two
int(*pointer_function)();
int *pointer_function();
Can somebody explain me the difference between the following?
float *pointer[10];
float *(pointer[10]);
int(*pointer_function)();
int *pointer_function();
These two declarations
float *pointer[10];
float *(pointer[10]);
are equivalent. You can write even the following way
float *( ( pointer )[10] );
That is it is a declaration of an array of 10 pointers to float.
These declarations
int(*pointer_function)();
int *pointer_function();
are different. The first one declares a pointer to a function of type int()
. The second one declares a function (not a pointer to a function) with type int *()
.
Here is a demonstrative program
#include <iostream>
int * pointer_function() // #1
{
static int x = 1'000'000;
return &x;
};
int f1() // #2
{
return 2'000'000;
}
int main()
{
std::cout << *pointer_function() /* calling #1 */<< '\n';
int( *pointer_function )() = f1;
std::cout << pointer_function() /* calling #2 */ << '\n';
return 0;
}
Its output is
1000000
2000000
To make more obvious the difference between the declarations you can rewrite the second declaration (that is the declaration of function) the following way
int * ( pointer_function )();
Compare it with the pointer to function declaration
int ( *pointer_function )();
Take into account that a declarator may be enclosed in parentheses.
Always keep in mind the place of Parentheses. Parentheses do not alter the type of the object, but they can alter the binding of complex declarators.
From above code snippet:
float *pointer[10];// Array of 10 pointer to float
float *(pointer[10]); //bracket around array of 10 pointer to float, So same as above
int(*pointer_function)(); // function pointer to achieve callbacks
int * pointer_function(); // function to integer pointer