当数组为空时,ARRAY_SIZE是否返回未定义的行为? [英] Does ARRAY_SIZE return undefined behaviour when the array is empty?
问题描述
当数组为空时,ARRAY_SIZE是否返回未定义的行为?因为我们做出了一个不存在的 sizeof((X)[0])
Is ARRAY_SIZE return undefined behaviour when the array is empty? because we make a devide of unexisting sizeof((X)[0])
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(X) sizeof((X))/sizeof((X)[0])
#endif
struct ka {
int a;
int b;
};
int main(void)
{
struct ka k[] = {};
printf("%d\n", ARRAY_SIZE(k));
}
推荐答案
不可能标准C或C ++中大小为零的数组。
It is not possible to have zero-sized arrays in Standard C or C++.
在C中,您的代码违反了约束(任何地方都不允许使用空的初始化列表)。
In C your code is a constraint violation (empty initializer lists are not permitted anywhere).
在C ++中这也是一个错误; {}
不能与忽略大小的数组定义一起使用。 (C ++ 14 [dcl.init.aggr] / 4)
In C++ it is also an error; {}
may not be used with an array definition that omits the size. (C++14 [dcl.init.aggr]/4)
如果您使用非标准的编译器扩展,则其行为将取决于该扩展的详细信息
If you use a non-standard compiler extension then the behaviour will depend on the details of that extension.
这篇关于当数组为空时,ARRAY_SIZE是否返回未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!