nikagra
nikagra

Reputation: 843

What does the following C++statement mean

There is a statement I saw in an C++ interview test today:

int (*(*fb)(int, char*))[2];

I have no idea what this declaration could mean. It looks much like function pointer but first star and square braces spoil everything.

Visual Studio decodes fb's type as following int[2] * (int, char *) *, which still looks like a bit cryptic.

If we simplify declaration than everything looks clear

int(*(*fa)(int, char*));

int* func(int, char*) 
{ 
    return 0; 
}

// now we can assign func to fa
fa = func;

Any ideas?

Upvotes: 1

Views: 168

Answers (3)

nikagra
nikagra

Reputation: 843

Colleague of mine have just sent an answer:

int (*(*fb)(int, char*))[2];

int(*(returnArray(int, char*)))[2]
{
    static int tab[2];
    return &tab;
}

// finally we have it
fb = returnArray;

I have no idea who can use this and for what purpose

Upvotes: 0

leemes
leemes

Reputation: 45665

fb is a function pointer of the following signature:

  • The function takes two parameters: int and char*
  • The function returns a pointer to an array of two int, which has the type int(*)[2]

Usually, because of the cryptic syntax of function pointers, array pointers and such stuff, you should use typedefs or type aliases (the new using-syntax) to make it clearer step by step:

using int2 = int[2];
using int2ptr = int2*;
using fb = int2ptr(int, char*);

Proof

Also, instead of returning arrays, you could consider returning a std::vector or std::array; instead of passing char pointers you could consider std::string, and instead of using function pointers you could consider std::function. All these are "coulds", since every "raw type" has its reason to exist, but the reasons are very limited.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It is a definition of pointer to function that has two parameters, one of type int and other of type char *, and returns pointer to array of type int[2].

Here is a simplified demonstrative program. I have only changed the second parameter to type const char *

#include <iostream>

int(*f( int x, const char *s ))[2]
{
    static int a[2] = { x, *s };

    return &a;
}

int main()
{
    int (*(*fb)(int, const char*))[2] = f;
    auto p = fb( 10, "A" );

    std::cout << ( *p )[0] << '\t' << ( char )( *p )[1] << std::endl; 
    return 0;
}

The output is

10  A

Upvotes: 1

Related Questions