Anakin Tung
Anakin Tung

Reputation: 419

C Initializer element is not constant [What's the difference between array and variable]

I have the following code-piece

 #include <stdio.h>

 int a[4];
 int b;
 struct test {
         int *ptr;
         int val;
 };

 struct test test_array[] = {
         {
                 a, //Don't understand here
                 b  //compile error 
         }
 };

 int main() {
         struct test ha = test_array[0];
         ha.ptr[0] = 10;
         printf("%d\n", ha.ptr[0]);
         return 0;
 } 

from the following link, I know why the compile error happens. C - initializer element is not constant

But just don't understand why static storage array is OK?

Thanks

Upvotes: 2

Views: 205

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

Initializers of global variables in C need to be constant expressions, and b is not a constant expression. (It's not even a const variable.) By contrast, the expression a is the address of the first element of the global array a, and addresses of global variables are constant expressions.

To answer your question at a higher level: The difference between a and b is that you are using the value of b but not the value of a, only its address.

Upvotes: 8

Hellmar Becker
Hellmar Becker

Reputation: 2972

b is not constant, as pointed out earlier. As for a, the variable's content is not constant either but all you take in your struct is the address of that array. And that is constant and known at compile time.

Upvotes: 0

Related Questions