first_order_logic
first_order_logic

Reputation: 75

Why won't this particular C code compile?

Consider:

#include <stdio.h>

int const NAMESIZE = 40;
int const ADDRSIZE = 80;
typedef char NameType[NAMESIZE];
typedef char AddrType[ADDRSIZE];

typedef struct
{
    NameType name;
    AddrType address;
    double salary;
    unsigned int id;
} EmpRecType;

int main(int * argc, char * argv[])
{
    EmpRecType employee;
    return 0;
}

If I use #define instead of const it compiles.

This is the error:

employee.c:5:14: error: variably modified 'NameType' at file scope
employee.c:6:14: error: variably modified 'AddrType' at file scope

Upvotes: 2

Views: 1047

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320481

One of the differences between C and C++ is that in C++ a const int object is a constant, i.e. it can be used to form constant expressions. In C, on the other hand, a const int object is not a constant at all (it's more like "unchangeable variable").

Meanwhile, array size for file scope arrays in C is required to be a constant expression, which is why your const int object does not work in that role. (The above means, BTW, that your code will compile perfectly fine as C++, but won't compile as C.)

In C language to define named constants you have to use either #define or enums. In your specific case it could be done as follows

#define NAMESIZE 40
#define ADDRSIZE 80

P.S. If you replace your file-scope arrays with local arrays, your C code will compile as is, i.e. with const int objects as array sizes, because modern C (ANSI C99) supports variable-length arrays (VLA) in local scope. (And your arrays will be VLA in that case). In older versions of C (like ANSI C89/90) the code will not compile even with local arrays.

Upvotes: 9

David Heffernan
David Heffernan

Reputation: 612964

Those const declarations, in C, just define some read only memory, they are not true constants. They can't be evaluated until runtime which is too late for the array declarations.

Upvotes: 7

Related Questions