标签:blog http io ar os sp 问题 log 代码
一下copy自:http://bbs.csdn.net/topics/90234659
-------------------------------------------------------------------------------------------------------------------
“两则C语言技巧”http://tb.blog.csdn.net/TrackBack.aspx?PostId=1120124
第一个技巧在我的环境下不能通过,是我的原因吗。
引用:
1. 数组初始化。
常见的数组初始化方法:
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
通常情况下,这种做法没有问题。再看看下面这个例子:
enum
{
FRUIT_APPLE,
FRUIT_PEAR,
FRUIT_BANANA,
FRUIT_NR
};
int price[FRUIT_NR] = {20, 25, 30};
这段代码有个潜在前提,那就是枚举的顺序不能变化。一旦变化,整个逻辑都乱了,这样的BUG能否查出来要靠运气。这样的假设是靠不住的,特别是当枚举是第三方库提供的时候,他们调整枚举的顺序后绝对不会通知你。为了避免这样的潜在隐患,可以用下面的方法:
Enum
{
FRUIT_APPLE,
FRUIT_PEAR,
FRUIT_BANANA,
FRUIT_NR
};
int price[FRUIT_NR] = { [FRUIT_APPLE] = 20, [FRUIT_PEAR] = 25, [FRUIT_BANANA] = 30};
而我的测试代码,不行啊:
//用枚举量做下标初始化数组。
#include <iostream>
enum
{
FRUIT_APPLE,
FRUIT_PEAR,
FRUIT_BANANA,
FRUIT_NR
};
int main()
{
using namespace std;
int price1[FRUIT_NR] = {20, 25, 30};
int price2[FRUIT_NR] =
{
[FRUIT_APPLE] = 20,
[FRUIT_PEAR] = 25,
[FRUIT_BANANA] = 30
};
int i = 0;
cout << "price1:\n";
cout << "apple, " << price1[i++] << ". ";
cout << "pear, " << price1[i++] << ". ";
cout << "banana, " << price1[i] << ". \n";
i = 0;
cout << "price2:\n"
cout << "apple, " << price2[i++] << ". ";
cout << "pear, " << price2[i++] << ". ";
cout << "banana, " << price2[i] << ". \n";
system("PAUSE");
return 0;
}
第二个技巧还不错。
标签:blog http io ar os sp 问题 log 代码
原文地址:http://www.cnblogs.com/xaf-dfg/p/4111255.html