0

Can somebody explain me the difference between the following?

  1. Those two
float *pointer[10];

float *(pointer[10]);
  1. and those two
int(*pointer_function)();

int *pointer_function();
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
coolchock
  • 99
  • 4
  • FWIW: [here](https://cdecl.org/) is a handy website to figure out some of the gibberish – NathanOliver May 28 '19 at 13:14
  • 1
    Me thinks 1. is a dupe of https://stackoverflow.com/questions/45991094/which-part-of-the-c-standard-allow-to-declare-variable-in-parenthesis and 2. is easy becuase those are quite different things, "pointer to a function" and "a function returning pointer (`int*`)". – luk32 May 28 '19 at 13:18
  • Would highlight this is why many people prefer `float* pointer[10]` rather than `float *pointer[10]` because the `float*` is the type – UKMonkey May 28 '19 at 14:00
  • @UKMonkey Many people prefer float * pointer[10]; :) – Vlad from Moscow May 28 '19 at 14:47
  • @VladfromMoscow it's better than `float *pointer[10]` when someone's trying to line up their variable names! – UKMonkey May 28 '19 at 14:51

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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
Arun Kumar
  • 151
  • 3
  • 10