在C++中for循环可以使用基于范围的for循环,示例代码如下
#include <iostream>
using namespace std;
void test01()
{
int arr[] = { 1,2,3,4,5,6,7,8,9, };
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; ++i)
{
cout << arr[i] << ",";
}
cout << endl;
for (int tmp : arr)
{
cout << tmp << ",";
}
cout << endl;
for (int i = 0; i < n; i++)
{
int &tmp = arr[i];
tmp = 2 * tmp;
cout << tmp << ",";
}
cout << endl;
for (int &tmp : arr)
{
tmp = 2 * tmp;
cout << tmp << ",";
}
cout << endl;
}
void test02(int arr[])
{
#if 0
for (auto e : arr)//编译失败,这从侧面说明形参中的数组是指针这一事实
{
cout << e << ",";
}
cout << endl;
#endif
}
int main(int argc, char ** argv)
{
test01();
system("pause");
return 0;
}
静态断言
c/c++提供了调试工具assert,这是一个宏,用于在运行阶段对断言进行检查,如果条件为真,执行程序,否则调用abort();
void test03()
{
bool flag = false;
// 如果条件为真,程序正常执行,如果为假,终止程序,提示错误
assert(flag == true); //#include <cassert>
cout << "hello world" << endl;
}
C++11新增了关键字static_assert,可用于在编译阶段进行测试。
静态断言的好处
- 更早的报告错误,我们知道构建是早于运行的,更早的错误报告意味着开发成本的降低
- 减少运行时开销,静态断言是编译期检测的,减少运行时开销
语法
static_assert(常量表达式,提示字符串);
注意:只能是常量表达式,变量在编译期间还没有分配内存(不存在)
void test04()
{
// 该static_assert用来确保编译仅在32位的平台上进行,不支持64位平台
static_assert(sizeof(void *) == 4, "64-bit code generation is not supported");
cout << "hello" << endl;
}