'C' seem to permit initialization of members of a structure inside a function as long as the storage class of the structure is not 'static', Trying to do so returns following compilation error:
error: initializer element is not constant
Code snip
typedef struct data {
int age;
char *name;
} data_t;
void foo(data_t student)
{
//data_t s1 = student; <--- works
static data_t s1 = student; <--- throws error
printf("%s: s1.age: %d, s1.name: %s\n",__FUNCTION__,s1.age, s1.name);
}
Appreciate, if you throw some insight.
Objects with static storage has to be initialized with constant expressions or with aggregate initializers containing constant expressions in C. You are trying to initialize the static declared object s1
by a non static object student
. That is why the compiler throws the error initializer element is not constant
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.