当前位置:网站首页>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);![]()
边栏推荐
猜你喜欢
随机推荐
ELK log analysis system
Google 安装印象笔记剪藏插件
canvas 像素操作(图片像素操作)
The original question on the two sides of the automatic test of the byte beating (arranged according to the recording) is real and effective 26
Matlab论文插图绘制模板第41期—气泡图(bubblechart)
MySQL夺命10问,你能坚持到第几问?
mysql 存储过程详解
Android studio connects to MySQL and completes simple login and registration functions
Introduction and use of apifox (1).
大屏UI设计-看这一篇就够了
el-input 只能输入整数(包括正数、负数、0)或者只能输入整数(包括正数、负数、0)和小数
100 latest software testing interview questions in 2022, summary of common interview questions and answers
MySQL 5.7详细下载安装配置教程
ORA-04044:此处不允许过程、函数、程序包或类型,系统分析与解决
2022年100道最新软件测试面试题,常见面试题及答案汇总
interrupt()、interrupted()和isInterrupted()你真的懂了吗
ApiPost is really fragrant and powerful, it's time to throw away Postman and Swagger
Google notes cut hidden plug-in installation impression
Detailed installation and configuration of golang environment
Navicat报错:1045 -拒绝访问用户[email protected](使用passwordYES)









