简体   繁体   中英

Anyone know why this C code won't compile?

#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

One of the differences between C and C++ is that in C++ a const int object is a constant , ie 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

PS If you replace your file-scope arrays with local arrays, your C code will compile as is, ie 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.

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.

Although the question has been answered, i think you should go through this link:

Incompatibilities Between ISO C and ISO C++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM