C++11:基于范围的for循环和静态断言

在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,可用于在编译阶段进行测试。
静态断言的好处

  1. 更早的报告错误,我们知道构建是早于运行的,更早的错误报告意味着开发成本的降低
  2. 减少运行时开销,静态断言是编译期检测的,减少运行时开销

语法
static_assert(常量表达式,提示字符串);
注意:只能是常量表达式,变量在编译期间还没有分配内存(不存在)

void test04()
{
	// 该static_assert用来确保编译仅在32位的平台上进行,不支持64位平台
	static_assert(sizeof(void *) == 4, "64-bit code generation is not supported");
	cout << "hello" << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值