Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 974
Logan Avatar asked Feb 03 '16 19:02

Logan


1 Answers

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);
  ...
}
like image 171
AnT Avatar answered Oct 15 '22 11:10

AnT