Manfred Weis
Manfred Weis

Reputation: 836

Declaring local const variables of anonymous struct in C

I have the following code:

void fn(){
   struct{
     int a;
     int b;
     } s1, s2;
   s1.a = 1;
   s1.b = 2;
   s2.a = 1 << s1.a;
   s2.b = 1 << s2.b;
}

what I have tried is to make the variables constant somehow, but I get a bunch of compiler errors when attempting to do it this way:

void fn(){
   const struct{
     int a;
     int b;
     } s1{.a = 1, .b = 2}, s2{.a = 1 << s1.a, .b = 1 << s1.b};
}
main.c:7:10: error: expected ';' at end of declaration
     } s1{.a = 1, .b = 2}, s2{.a = 1 << s1.a, .b = 1 << s1.b};
         ^
         ;
1 error generated.

Question:

is there a solution for the problem of declaring two constant local variables s1 and s2 of the same anonymous struct with the fields of s2 defined via the fields of s1?

Upvotes: 3

Views: 403

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81926

You just forgot the = signs.

void fn(){
  const struct {
    int a;
    int b;
  } s1 = {
    .a = 1,
    .b = 2,
  }, s2 = {
    .a = 1 << s1.a,
    .b = 1 << s1.b,
  };
}

Upvotes: 6

Related Questions