2.2.4 名字的作用域

本文通过两个C++实例探讨了变量的作用域和生命周期。练习2.13展示了局部变量如何遮蔽全局变量,强调了作用域规则。练习2.14解释了for循环内变量在循环结束后无法再被访问,提醒开发者注意变量的生命周期及其影响。

在这里插入图片描述
练习2.13

#include <iostream>
using namespace std;
int i = 42;
int main() {
	
	int i = 100;
	int j = i;
	cout << "j = " << j << endl;

	system("pause");
}

输出发生在局部变量i定义之后,此时局部变量i
正在作用域内,因此输出语句使用的是局部变量i而非全局变量。在这里插入图片描述
练习2.14

#include <iostream>
using namespace std;

int main() {
	
	int i = 100, sum = 0;
	for (int i = 0; i != 10; ++i)
		sum += i;
	cout << i << " " << sum << endl;

	system("pause");
}

在for语句中的int定义于for语句内,在for语句中可以访问int,但是在循环结束之后,此变量的值不能再被访问。当for语句循环结束时,此时for语句中的int实际等于9但不可再被访问,sum被赋值等于100。而函数体内的int仍然等于100。所以注意不要重复初始化以及注意变量的作用域。
在这里插入图片描述

0501@DESKTOP-NBE1KN5 MINGW64 /d/work/common-framework-webapp/docs $ pnpm add @jzetech/tailwind-config -D .. |  WARN  `node_modules` is present. Lockfile only installation will make it out-of-date ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4  ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@jzetech%2Ftailwind-config: Not Found - 404 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4  ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@jzetech%2Ftailwind-config: Not Found - 404 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4  ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@jzetech%2Ftailwind-config: Not Found - 404 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4 ../internal/node-utils |  WARN  deprecated @types/chalk@2.2.4  ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@jzetech%2Ftailwind-config: Not Found - 404 This error happened while installing a direct dependency of D:\work\common-framework-webapp\docs @jzetech/tailwind-config is not in the npm registry, or you have no permission to fetch it. No authorization header was set for the request. ../packages/@core/base/shared |  WARN  deprecated lodash.isequal@4.5.0 .. | Progress: resolved 161, reused 0, downloaded 0, added 0能看出是那个包需要这个包吗
最新发布
08-15
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值