4

In the below code, I am trying to assign function pointer to array of function pointers. I get the error message

error: initializer element is not constant and then a note says near initialization for 'stateTable2[1]'.

In main, I tried to assign function pointer to another function pointer and no issue.

void function1 (void) // Function definition
{

}

void function2 (void) // Function definition
{

}

void (*fptr)(void) = function2;

void (*stateTable2[]) (void) = {function1,fptr};

int main()
{
    void(*fp)(void) = fptr;
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Rajesh
  • 1,085
  • 1
  • 12
  • 25
  • In main, you are declaring, not assigning. Just try `fptr = function1;` – Mawg says reinstate Monica Mar 15 '18 at 10:43
  • 2
    In `main` you have an initialization at runtime. As with assignments you don't need constant expression here. For initialization of data objects with static duration you need a constant expression. – Gerhardh Mar 15 '18 at 10:46
  • 1
    ... therefore `void (*stateTable2[]) (void) = {function1,fptr};` -> `void (*stateTable2[]) (void) = {function1, function2};` – Jabberwocky Mar 15 '18 at 10:47

1 Answers1

5

You may not initialize an array with the static storage duration with a non-constant object.

Either declare the array like

void (*stateTable2[]) (void) = { function1, function2 };

or move the declaration

void (*stateTable2[]) (void) = {function1,fptr};

inside main making the array as an array with automatic storage duration.

Here is a demonstrative program.

#include <stdio.h>

void function1 (void) // Function definition
{
    printf( "Hello " );
}

void function2 (void) // Function definition
{
    puts( "World!" );
}

void (*fptr)(void) = function2;

int main(void) 
{
    void ( *stateTable2[] ) (void) = { function1, fptr };
    void(*fp)(void) = fptr;

    fp();

    for ( size_t i = 0; i < sizeof( stateTable2 ) / sizeof( *stateTable2 ); i++ )
    {
        stateTable2[i]();
    }

    return 0;
}

Its output is

World!
Hello World!
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • How come preprocessor can understand the function name but not function pointer? I thought initializing fptr happens during preprocessing (hence it is known during compile time). But it looks this is not the case. – Rajesh Mar 15 '18 at 16:54
  • @Rajesh: You might want to elaborate more on what you mean. – stephanmg Feb 12 '20 at 15:40