我刚刚在 C++ 中有一个讨厌的错误。所以我有寄存器和值的列表,它们被包装在一个结构中,然后这些结构在一个数组中被初始化。但后来我不小心输入()
了{}
. 这是一些测试代码:
#include <stdio.h>
struct reg_val {
unsigned reg;
unsigned val;
};
struct reg_val faulty_array[] = {
{0x5001, 0xff},
{0x5580, 0x01},
(0x5580, 0x02), //<- THIS LINE IS THE PROBLEM
(0x5589, 0x00), //<- AND THIS LINE
};
struct reg_val good_array[] = {
{0x5001, 0xff},
{0x5580, 0x01},
{0x5580, 0x02},
{0x5589, 0x00},
};
int main()
{
unsigned i;
unsigned faulty_size = sizeof(faulty_array) / sizeof(struct reg_val);
printf("Size of faulty array: %d\n", faulty_size);
for (i = 0; i < faulty_size; ++i) {
printf("faulty reg: %x val: %x\n", faulty_array[i].reg,
faulty_array[i].val);
}
unsigned good_size = sizeof(good_array) / sizeof(struct reg_val);
printf("\nSize of good array: %d\n", good_size);
for (i = 0; i < good_size; ++i) {
printf("good reg: %x val: %x\n", good_array[i].reg,
good_array[i].val);
}
return 0;
}
我对 C 更熟悉,令我惊讶的是,这仍然是用 g++ 编译的:
$ g++ -Wall array.cc
array.cc:11: warning: left-hand operand of comma has no effect
array.cc:12: warning: left-hand operand of comma has no effect
array.cc:13: warning: missing braces around initializer for ‘reg_val’
$ ./a.out
Size of faulty array: 3
faulty reg: 5001 val: ff
faulty reg: 5580 val: 1
faulty reg: 2 val: 0 <-- the first value gets discarded as mentioned in the compiler warning
Size of good array: 4
good reg: 5001 val: ff
good reg: 5580 val: 1
good reg: 5580 val: 2
good reg: 5589 val: 0
这段代码显然无法用 C 编译器编译,C++ 有什么区别使 C++ 编译器(尽管不情愿地)接受这段代码?