3

In standard Section ยง6.8 of the Standard (N3690 draft) I see this weird piece of code :

struct T2 { T2(int){ } };
int a, (*(*b)(T2))(int), c, d;

What is int(*(*b)(T2))(int) ?!

Is b a pointer to T2's constructor ?! or maybe a pointer to function pointer ?

It's weird that the bellow code also compile fine !:

struct T2 { T2(int){ } };
int((*b)(T2));
Serjik
  • 10,543
  • 8
  • 61
  • 70
uchar
  • 2,552
  • 4
  • 29
  • 50
  • 2
    Use the [spiral rule](http://c-faq.com/decl/spiral.anderson.html). `b` is a pointer to a function taking a `T2` and returning a pointer to a function taking `int` and returning `int`. Broader form of this question: http://stackoverflow.com/questions/89056/how-do-you-read-c-declarations โ€“ chris Aug 11 '14 at 13:23

3 Answers3

9
int (*(*b)(T2))(int) 

It declares b as pointer to a function which:

  • takes T2 as argument
  • and returns pointer to a function which
    • takes an int as argument
    • and returns an int.

One should simplify this declaration using typedefs as:

typedef int (*return_type) (int);
typedef return_type(*function_type) (T2);

Or better use C++11 style type aliases:

using return_type   = int(*)(int);
using function_type = return_type(*)(T2);

Then the declaration becomes this:

function_type b; //so simple!

Hope that helps.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • And `int((*b)(T2));` is equal to `int(*b)(T2);` ? โ€“ uchar Aug 11 '14 at 13:40
  • 2
    @omid: Yes. The extra parenthesis are superfluous. So you can write even this `int(((((*b)(T2)))))` which is same as `int(*b)(T2)`. โ€“ Nawaz Aug 11 '14 at 13:42
1

It is declaration of variable b. b is a pointer to function with one parameter of type T2. The return type of this function is pointer to function with one parameter int returning int.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

This should help you understand what is going on here:

struct T2 { T2(int){ } };

typedef int (*func)(int);

int
(*foo(T2))(int) {
}

func
bar(T2) {
}

int main() {
    int (*(*b)(T2))(int);

    b = &foo;
    b = &bar;

    return 0;
}

So this is a function that take a T2 and return a function pointer to a function that return an int and take an int as parameter.

I a add this to my example of why c(++) is an horrible language.

By the way, you cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.")

vhb
  • 31
  • 1
  • 4