V
V.Subramanian, India
consider the following program x.c:
#include <stdlib.h>
#include <stdio.h>
char first[] = "test message";
void display(void)
{
static char* p_first = first + 5;
printf("%s\n", p_first);
char second[] = "new message";
static char* p_second = second + 4;
printf("%s\n", p_second);
return;
}
int main()
{
display();
return EXIT_SUCCESS;
}
When this program is compiled with
gcc (GCC) 3.4.3 20050227 (Red Hat 3.4.3-22.1)
as
gcc -std=c99 -pedantic -Wall -Wextra x.c
it generates the following error:
x.c: In function `display':
x.c:13: error: initializer element is not constant
The compiler accepts the initialization of the local static variable
'p_first' in 'display()' function. However the compiler reports error
for the initializtion of the local static variable 'p_second' in
'display()' function.
In the case of 'p_first', the array name 'first' decays into a pointer
to the first element and so in this case ALSO the memory address
stored in p_first will be known only at run-time(similar to that of
'p_second'). So why doesn't the compiler flag this as an error ?
Please clarify.
Thanks
V.Subramanian
#include <stdlib.h>
#include <stdio.h>
char first[] = "test message";
void display(void)
{
static char* p_first = first + 5;
printf("%s\n", p_first);
char second[] = "new message";
static char* p_second = second + 4;
printf("%s\n", p_second);
return;
}
int main()
{
display();
return EXIT_SUCCESS;
}
When this program is compiled with
gcc (GCC) 3.4.3 20050227 (Red Hat 3.4.3-22.1)
as
gcc -std=c99 -pedantic -Wall -Wextra x.c
it generates the following error:
x.c: In function `display':
x.c:13: error: initializer element is not constant
The compiler accepts the initialization of the local static variable
'p_first' in 'display()' function. However the compiler reports error
for the initializtion of the local static variable 'p_second' in
'display()' function.
In the case of 'p_first', the array name 'first' decays into a pointer
to the first element and so in this case ALSO the memory address
stored in p_first will be known only at run-time(similar to that of
'p_second'). So why doesn't the compiler flag this as an error ?
Please clarify.
Thanks
V.Subramanian