简体   繁体   English

有谁知道为什么这个C代码不会编译?

[英]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. 如果我使用#define而不是const它编译。 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 employee.c:5:14:错误:在文件范围employee.c:6:14:错误地修改了'NameType':在文件范围内修改了'AddrType'

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 . C和C ++之间的区别之一是在C ++中, const int对象是一个常量 ,即它可以用于形成常量表达式 In C, on the other hand, a const int object is not a constant at all (it's more like "unchangeable variable "). 另一方面,在C中, const int对象根本不是常量(它更像是“不可变的变量 ”)。

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. 同时,C中文件范围数组的数组大小必须是一个常量表达式 ,这就是你的const int对象在该角色中不起作用的原因。 (The above means, BTW, that your code will compile perfectly fine as C++, but won't compile as C.) (上面的意思是BTW,你的代码将作为C ++完全编译,但不会编译为C.)

In C language to define named constants you have to use either #define or enums. 在C语言中定义命名常量,您必须使用#define或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. PS如果用本地数组替换文件范围数组,则C代码将按原样编译,即使用const int对象作为数组大小,因为现代C(ANSI C99)支持本地范围内的可变长度数组(VLA)。 (And your arrays will be VLA in that case). (在这种情况下,你的阵列将是VLA)。 In older versions of C (like ANSI C89/90) the code will not compile even with local arrays. 在旧版本的C(如ANSI C89 / 90)中,即使使用本地数组,代码也无法编译。

Those const declarations, in C, just define some read only memory, they are not true constants. 这些const声明在C中只定义了一些只读内存,它们不是真正的常量。 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++ ISO C和ISO C ++之间的不兼容性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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