-2

I am getting error when i am initializing the structure in below form

static struct A* a = &apple->queue[queue_number];
static struct B* b = &banana->queue_a[queue_number];

I am getting error

Error:  #28: expression must have a constant value

I want to keep pointer a and b as static so that it's scope remain in same file. Please help here

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Let me guess: The variables `a` and `b` are global variables? Those needs to be initialized to compile-time constants, you can not use run-time variables for that. Please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve), so we don't have to guess. – Some programmer dude May 05 '18 at 09:35
  • It must be a constant value. This means **compile time constant**. Without seeing more of your code, it's impossible to suggest what you could do instead. –  May 05 '18 at 09:35
  • Is `&apple->queue[queue_number]` known at compile time? Only then it can be used to initialise static and/or global variables. – alk May 05 '18 at 09:39
  • @alk which, in C, would AFAIR require at least `queue_number` to be a `#define` -- a static `const` won't do here... –  May 05 '18 at 09:41
  • @FelixPalmen: Fair enough ... the term "*known at compile*" is ambiguous as well. :-/ – alk May 05 '18 at 09:47
  • @alk especially because C++ would allow a `const` with static linkage ;) For a good answer, you'd probably write a chapter of a book :( –  May 05 '18 at 09:48
  • This `int i = 0; int * pi = &i;` would do in global scope. The address of `i` is "*known at compile time*". – alk May 05 '18 at 09:52

1 Answers1

1

Its because a is of static type and it should be initialize with constants or values of variable(in your case its &apple->queue[queue_number]) known at compile time not at run time. From the C standard

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

I want to keep pointer a and b as static ? One way to do is initialize first a with NULL & test it.

static struct A *a = NULL;
if(a == NULL) { /* point to remember when a become NULL it initialize again a */
        a = &apple->queue[queue_number]; /*initialize expected value here */ 
}

May be you want to read this Error "initializer element is not constant" when trying to initialize variable with const

Achal
  • 11,821
  • 2
  • 15
  • 37
  • 1
    You might want to in more detail explain what "constant" means in *this* context, as it unfortunately is used somewhat ambiguous by the C Standard. – alk May 05 '18 at 09:39
  • 2
    Instead of a separate flag variable,initialilze the pointer to `NULL`, and test that. – Barmar May 05 '18 at 09:47
  • yes @Barmar that's a good idea instead of separate flag variable – Achal May 05 '18 at 09:49
  • Click my answer as accepted if it really help you @sobincoder – Achal May 07 '18 at 07:05