Declaring an array of functions like void C ++

I have several functions that return void. I made pointers to these functions and wanted to have an array of these functions:

Why does this code work:

#include <cstdio>
using std::puts;

void tell() {
  puts("hi");
};

void slap() {
  puts("goodbye");
}

int main(int argc, char *argv[])
{

  void (*tp)() = tell;
  void (*sp)() = slap;

  void(*funcs[])() = {tp, sp};
  for (auto point:funcs) {
    point();
  }
  return 0;
}

When I try to execute this code without specifying a pointer in funcs(i.e. void(funcs[])() = {tp, sp};, I get " error: 'funcs' declared as array of functions of type 'void ()' "what exactly is what they are - so why is this an error?

I also don't get the syntax, doesn't that mean ()at the end it void(*funcs[])()points to a function call?

+4
source share
4 answers

The C ++ 8.3.5 / 10 standard says:

There should not be arrays of functions, although there may be arrays of pointers to functions.

"funcs" " ":

funcs[]: funcs -

*funcs[]: funcs -

(*funcs[])(): funcs -

void (*funcs[])(): funcs - , void.

+4

void (funcs[])() , . ++, - .

[dcl.array]/1:

T ; , ( cv-qualit) void, .

({tp, sp}) - , :

[conv.func]/1

T prvalue " T". .

, ++ .


, () void(*funcs[])() ?

, . () , . " , (()) void". :

using void_f = void (*)();
void_f funcs[] = {tp, sp};
+2

:

void (*actions[5])();

. , typedef.

typedef void(*Action)();    // Action is the typename for a pointer
                            // to a function return null and taking
                            // no parameters.

Action   actions[5];        // An array of 5 Action objects.

:

int main()
{
     Action   actions[] = {&tell, &slap};
}
+2
source

use the following:

int main(int argc, char *argv[])
{
    void (*tp)() = tell;
    void (*sp)() = slap;

    void (*funcs[])() = {tp, sp};
    for (void (*point)():funcs)
    {
        point;
    }
    return 0;
}
-1
source

Source: https://habr.com/ru/post/1599773/


All Articles