C struct object Stack - function call is not allowed in constant expression (error)

25,752

In C language objects with static storage duration can only be initialized with constant expressions.

You are initializing a global variable S, which is an object with static storage duration. Your expression newStack(256) is not a constant expression. As the compiler told you already, you are not allowed to call functions in constant expressions. Hence the error. That's all there is to it.

If you want to have a global variable S, then the only way to "initialize" it with newStack(256) is to do it inside some function at program startup. E.g.

Stack * S;

int main()
{ 
  S = newStack(256);
  ...
}
Share:
25,752
Logan
Author by

Logan

Freelance programmer Java, Android, Xml, C, Arduino

Updated on July 09, 2022

Comments

  • Logan
    Logan almost 2 years

    I am trying to create a struct object (stack) which consists of:

    typedef struct node {
        int val;
        struct node * next;
    }node_t;
    
    typedef struct {
        node_t * top;
        int max_size;
        int used_size;
    } Stack;
    

    However, when I try to initialize the object and allocate it some memory space using the function:

     Stack * newStack(int max_size) {
        Stack * S = malloc(sizeof(Stack));
        S->top = NULL;
        S->max_size = max_size;
        S->used_size = 0;
        return S;
    }
    
    Stack * S = newStack(256); //error here
    

    I get the error referred to above -

    function call is not allowed in constant expression

    I have never come across this type of error before, and I don't know how to tackle it. Any help is appreciated.

  • AnT stands with Russia
    AnT stands with Russia over 8 years
    @pm100: Yes, C++ allows this, but the question is about C.
  • pm100
    pm100 over 8 years
    i was telling the OP that if he changed to c++ he can do what he wants (if thats an option)
  • Logan
    Logan over 8 years
    I see, embedded the line in a function and worked. Much obliged!