#include <stdio.h>
void foo(void){ printf("helloworld\n"); return; }
void (* foo2)(void) = foo;
struct data {void (* fptr)(void);};
static struct data myarray[] = {
{foo},
{foo2}, //THIS must be commented for the code to work!!!!
};
int main(){myarray[0].fptr(); return 0; }
and THIS generates the following error:
test.c:7: error: initializer element is not constant
test.c:7: error: (near initialization for ‘myarray[1].fptr’)
Can I fix it by placing a "const" in the right position?
I was thinking to use "(* const foo2)" but it doesn't change a thing.
Thanks in advance
RM
> I already asked something similar: I have this code
>
> #include <stdio.h>
> void foo(void){ printf("helloworld\n"); return; }
> void (* foo2)(void) = foo;
> struct data {void (* fptr)(void);};
> static struct data myarray[] = {
> {foo},
> {foo2}, //THIS must be commented for the code to work!!!!
> };
> int main(){myarray[0].fptr(); return 0; }
>
> and THIS generates the following error:
> test.c:7: error: initializer element is not constant
> test.c:7: error: (near initialization for ‘myarray[1].fptr’)
>
> Can I fix it by placing a "const" in the right position?
Not in standard C. The permitted forms for an address constant don't
include the value of another object like foo2 no matter how it is
qualified.
> I was thinking to use "(* const foo2)" but it doesn't change a thing.
--
Ben.
No!
The address of a function is not a compile time constant - it doesn't
get assigned until the function is linked (possibly dynamically at
runtime).
Use assignment rather than initialization:
static struct data myarray[2];
myarray[0].fptr = foo;
myarray[1].fptr = foo2;
No.
--
Best regards,
Andrey Tarasevich
#include <stdio.h>
void
foo (void)
{
printf ("helloworld\n");
return;
}
void (* foo2)(void) = foo;
struct data
{
void (* fptr)(void);
};
static struct data myarray[2] = {
{foo},
// {foo2}, //THIS must be commented for the code to work!!!!
};
int
main()
{
myarray[1].fptr = foo2;
myarray[0].fptr();
return 0;
}
---------------------------------------------------------
hi,my english is pool,but this is code ok! it compiled ok by gcc.
and your code compiled ok by g++.use g++ to have a try!
---
baozf
Wrong -- it's an address constant, which qualifies as a constant
expression and is thus valid in a static initializer. The value of a
variable, however, is never a constant expression, not even if the
variable is declared const.
--
Larry Jones
Ha! Wild zontars couldn't drag that information out of me! Do your worst!
-- Calvin
>The address of a function is not a compile time constant - it doesn't
>get assigned until the function is linked (possibly dynamically at
>runtime).
It's the job of the linker to fix this up, just as it has to fix up
straightforward calls to the function.
-- Richard
--
Please remember to mention me / in tapes you leave behind.