当前位置:网站首页>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);![]()
边栏推荐
猜你喜欢

数学建模笔记:TOPSIS方法(优劣解距离法)和熵权法修正

MySQL 8.0.29 set and modify the default password

ApiPost is really fragrant and powerful, it's time to throw away Postman and Swagger

MySQL 8.0.29 decompressed version installation tutorial (valid for personal testing)

navicat新建数据库

ORA-04044:此处不允许过程、函数、程序包或类型,系统分析与解决
![[PSQL] window function, GROUPING operator](/img/95/5c9dc06539330db907d22f84544370.png)
[PSQL] window function, GROUPING operator

MySQL 8.0.28 version installation and configuration method graphic tutorial

MySQL(7)

MySQL multi-table association one-to-many query to get the latest data
随机推荐
matlab simulink 模糊pid结合smith控制温度
LeetCode brush topic series - 787 K station transfer within the cheapest flight
面试测试工程师一般会问什么?测试主管告诉你
整合ssm(一)
18 years of programmer career, read more than 200 programming books, pick out some essence to share with you
行测不会概念
CAN光端机解决泰和安TX3016C消防主机长距离联网问题 实现CAN与光纤之间的双向数据智能转换
MySQL 5.7 detailed download, installation and configuration tutorial
MySQL 游标
Go语学习笔记 - grpc serverclient protobuf 从零开始Go语言
Go语言中定时任务库Cron使用详解
简道云-灵活易用的应用搭建平台
mysql实现按照自定义(指定顺序)排序
系统(层次)聚类
navicat connects to MySQL and reports an error: 1045 - Access denied for user 'root'@'localhost' (using password YES)
Detailed installation and configuration of golang environment
apisix-Getting Started
Mysql实现乐观锁
swinIR论文阅读笔记
MySql字符串拆分实现split功能(字段分割转列、转行)