0

I'm trying to use a queue in my program, but it won't compile and I don't know why. The relevant part of the code is as follows.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#ifndef CUSTOMER
#define CUSTOMER


typedef int bool;

int r;

typedef struct{

    int arrival;
    int leaving;

} Customer;


static const int MAX_LENGTH = 100;

typedef struct{
    int head;
    int length;

    Customer customer[MAX_LENGTH];

} CustomerLine;

void initializeQueue(CustomerLine* queue)
{
    (*queue).head = 0;
    (*queue).length = 0;
}

bool hasNext(CustomerLine* queue)
{
    return (*queue).length > 0;
}

bool isFull(CustomerLine* queue)
{
    return (*queue).length == MAX_LENGTH;
}

bool enqueue(CustomerLine* queue, Customer* customer)
{


    if(isFull(queue))
        return 0;
    int index = ((*queue).head + (*queue).length) % MAX_LENGTH;
    (*queue).customer[index] = *customer;
    (*queue).length++;

    return 1;
}

Customer* dequeue(CustomerLine* queue)
{
    if(!hasNext(queue))
        return 0;

    Customer* result = &(*queue).customer[(*queue).head];

    (*queue).length--;
    (*queue).head = ((*queue).head + 1) % MAX_LENGTH;
    return result;
}

The error says:

variably modified 'customer' at file scope

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3050546
  • 11
  • 1
  • 2
  • Possible duplicate: *[Variably modified array at file scope in C](https://stackoverflow.com/questions/13645936/variably-modified-array-at-file-scope-in-c)*. – Peter Mortensen Jul 29 '23 at 09:30
  • Does this answer your question? [Variably modified array at file scope in C](https://stackoverflow.com/questions/13645936/variably-modified-array-at-file-scope-in-c) – Peter Mortensen Aug 13 '23 at 19:55

2 Answers2

2

The line

static const int MAX_LENGTH = 100

is the problem. Replace it with

#define MAX_LENGTH  100

See why here and more explanations here or here or again here.

Furthermore:

  • You need an #endif after the #ifndef.
  • You need a main function somewhere.
Community
  • 1
  • 1
damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • Yeah thanks that did solve my problem. also note that i didnt post the full code (its for a class and i dont want to be copied). – user3050546 Nov 29 '13 at 22:13
1

In C, const means read-only, not constant and usable just like a macro. You cannot use a variable to specify the dimension of an array as you do here:

static const int MAX_LENGTH = 100;
typedef struct{
   int head;
   int length;
   Customer customer[MAX_LENGTH];  /* Wrong. MAX_LENGTH is not a compile time constant. */
} CustomerLine;
Jens
  • 69,818
  • 15
  • 125
  • 179