1
votes

My aim is to initialize a local static int variable. I want to initialize my variable with the value that equals to offset value of a struct member.

My struct definition

    struct member{
       int ID;
       char *NAME;
       int NO;
    };

Global Struct declaration

struct member FirstMember={.ID = 123, .NAME ="John", .NO=7382737};
struct member SecondMember={.ID = 120, .NAME ="Bill", .NO=454545};

Function and local static variable declaration

    void foo()
    {
       static int offset = (int)(&FirstMember.NO - &SecondMember.ID ); 
    }

Compiler output: Error[Pe028]: expression must have a constant value..

As far as I know static local variables must be initialized with const values. Compiler also knows the address values of the struct and its members. So compiler is able to calculate the difference between member addresses. But it returns an error message.

But this initialization works

void foo()
{
   static int offset = (int)(&FirstMember.NO - &FirstMember.ID );  
}

Could you please explain the point that I missed?

1

1 Answers

0
votes

I think the problem is in your structure declaration: Name shoul be "char *" not "char" because you try to initialize it with "John" (type const char *).

This is working for me:

struct member{
   int ID;
   char* NAME;
   int NO;
   };

struct member FirstMember={123,"John",7382737};

void foo()
{
   static int offset = (int)(&FirstMember.NO - &FirstMember.ID ); 
}

The second problem is that you want to initialize a "static" variable with an unknown value before run time. All the static variables are in a separate place named "initialized data" section and the compiler needs to know exactly the value of each static variable at compile time because these values are "hardcoded" inside your binary file.

Even for this code:

int a = 10;
static int x = a;

you will have the same problem because "a" is not evaluated at compile time but at run-time.