当前位置:网站首页>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);![]()
边栏推荐
- Redis-集群模式(主从复制模式,哨兵模式,集群化模式)
- Packaging and deployment of go projects
- 自动化运维工具——ansible、概述、安装、模块介绍
- Mysql实现乐观锁
- How much does a test environment cost? Start with cost and efficiency
- matlab simulink 飞机飞行状态控制
- MySQL安装教程
- c语言:查漏补缺(三)
- Navicat报错:1045-Access denied for user [email protected](using passwordYES)
- MySQL 8.0.29 decompressed version installation tutorial (valid for personal testing)
猜你喜欢
随机推荐
JUC(二)原子类:CAS、乐观锁、Unsafe和原子类
mysql 查询表 所有字段
MySQL夺命10问,你能坚持到第几问?
Matlab paper illustration drawing template No. 41 - bubble chart (bubblechart)
Matlab学习第二天
MySQL 字符串拼接 - 多种字符串拼接实战案例
matlab simulink 模糊pid结合smith控制温度
Mysql存储json格式数据
Mysql return table
大屏UI设计-看这一篇就够了
prisma使用mongodb副本集群报错引发的一些列问题
18 years of programmer career, read more than 200 programming books, pick out some essence to share with you
[Digital IC hand-tear code] Verilog fixed priority arbiter | topic | principle | design | simulation
The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
classSR论文阅读笔记
Navicat new database
PSQL function, predicate, CASE expression and set operations
MySQL 8.0.29 解压版安装教程(亲测有效)
MySQL 5.7详细下载安装配置教程
apisix-入门使用篇









