当前位置:网站首页>C语言中i++和++i在循环中的差异性
C语言中i++和++i在循环中的差异性
2022-08-02 05:06:00 【摆烂的神】
前言
今天刷题时遇到的,浅浅记录一下(可能就我不知道)。C语言中i++和++i都表示自增,不同的是++i是先增加再赋值,而i++是先赋值在增加。我觉得有和我一样的初学者,在之前一直有疑问:它们两个都差不多,那到底什么时候用i++,什么时候用++i?今天才了解到原来i++和++i在循环中的判断机制也不一样。
FOR循环
for循环中i++和++i是一样的,都是先判断再相加。
for (int i = 0; i < 5; i++)
{
cout << i << " ";
}
for (int i = 0; i < 5; ++i)
{
cout << i << " ";
}输出结果是一样的。
![]()
while循环
在while循环中,i++和++i就不一样了:i++是先判断再增加再进入循环体:
int i = -5;
while (i++ < 0)
{
cout << i << " ";
}如上代码中,先判断i == -5满足小于零,再自增 i = i + 1,最后进循环;
而++i则是先增加再判断再进入循环体:
i = -5;
while (++i < 0)
{
cout << i << " ";
}如上代码中,先自增 i = i + 1,再判断 i == -4 满足小于零,最后进循环;
测试结果如下:
![]()
do-while循环
在do-while循环中和while循环中的i++和++i是一样的,只不过do-while先执行了一次循环体:
cout << "do-while循环i++:";
i = -5;
do
{
cout << i << " ";
} while (i++ < 0);
cout << "do-while循环++i:";
i = -5;
do
{
cout << i << " ";
} while (++i < 0);![]()
边栏推荐
- 去字节跳动自动化测试二面原题(根据录音整理)真实有效 26
- Introduction and use of apifox (1).
- MySql将一张表的数据copy到另一张表中
- navicat连接MySQL报错:1045 - Access denied for user ‘root‘@‘localhost‘ (using password YES)
- ERROR 1045 (28000) Access denied for user 'root'@'localhost'Solution
- How much does a test environment cost? Start with cost and efficiency
- MySQL夺命10问,你能坚持到第几问?
- Mysql常用命令大全
- coredns介绍
- Navicat cannot connect to mysql super detailed processing method
猜你喜欢

Go语学习笔记 - 处理超时问题 - Context使用 从零开始Go语言

Detailed explanation of the software testing process (mind map) of the first-tier manufacturers

Mysql存储json格式数据

简道云-灵活易用的应用搭建平台

2022年100道最新软件测试面试题,常见面试题及答案汇总

How much does a test environment cost? Start with cost and efficiency

Use the browser's local storage to realize the function of remembering the user name

MySQL 8.0.29 set and modify the default password
[email protected](using passwordYES)"/>Navicat报错:1045-Access denied for user [email protected](using passwordYES)

Google notes cut hidden plug-in installation impression
随机推荐
Brush LeetCode topic series - 10. Regular expression match
LeetCode刷题系列 -- 10. 正则表达式匹配
165.比较版本号
大屏UI设计-看这一篇就够了
MySQL如何创建用户
ApiPost is really fragrant and powerful, it's time to throw away Postman and Swagger
Go语学习笔记 - 处理超时问题 - Context使用 从零开始Go语言
Mysql implements optimistic locking
[PSQL] 窗口函数、GROUPING运算符
MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
el-input 只能输入整数(包括正数、负数、0)或者只能输入整数(包括正数、负数、0)和小数
2022年100道最新软件测试面试题,常见面试题及答案汇总
PSQL function, predicate, CASE expression and set operations
golang's time package: methods for time interval formatting and output of timestamp formats such as seconds, milliseconds, and nanoseconds
21天学习挑战赛安排
go语言中的goroutine(协程)
服务器的单机防御与集群防御
The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
【C语言】LeetCode26.删除有序数组中的重复项&&LeetCode88.合并两个有序数组
Mysql return table