当前位置:网站首页>Differences between i++ and ++i in loops in C language
Differences between i++ and ++i in loops in C language
2022-08-02 06:20:00 【rotten god】
Foreword
I encountered it when I was brushing the questions today, and I recorded it in a shallow way (maybe I don't know).In the C language, i++ and ++i both represent self-increment, the difference is that ++i is incremented first and then assigned, while i++ is incremented first.I think there are beginners like me who have been wondering before: they are both similar, so when to use i++ and when to use ++i?I just learned today that the judgment mechanism of i++ and ++i in the loop is different.
FOR loop
i++ and ++i are the same in the for loop, they are both judged first and then added.
for (int i = 0; i < 5; i++){cout << i << " ";}for (int i = 0; i < 5; ++i){cout << i << " ";}
The output is the same.
while loop
In the while loop, i++ and ++i are different: i++ is judged first, then incremented, and then entered into the loop body:
int i = -5;while (i++ < 0){cout << i << " ";}
In the above code, first judge that i == -5 is less than zero, then increment i = i + 1, and finally enter the loop;
And ++i is to increase first, then judge and then enter the loop body:
i = -5;while (++i < 0){cout << i << " ";}
In the above code, first increment i = i + 1, then judge that i == -4 is less than zero, and finally enter the loop;
The test results are as follows:
do-while loop
The i++ and ++i in the do-while loop are the same as in the while loop, except that the do-while executes the loop body first:
cout << "do-while loop i++:";i = -5;do{cout << i << " ";} while (i++ < 0);cout << "do-while loop++i:";i = -5;do{cout << i << " ";} while (++i < 0);
边栏推荐
- leetcode每天5题-Day04
- 【合集- 行业解决方案】如何搭建高性能的数据加速与数据编排平台
- Detailed explanation of the software testing process (mind map) of the first-tier manufacturers
- 为什么4个字节的float要比8个字节的long大呢?
- [PSQL] window function, GROUPING operator
- C语言入门实战(13):十进制数转二进制
- C语言基础知识梳理总结:零基础入门请看这一篇
- 说好的女程序员做测试有优势?面试十几家,被面试官虐哭~~
- 金山云团队分享 | 5000字读懂Presto如何与Alluxio搭配
- 18年程序员生涯,读了200多本编程书,挑出一些精华分享给大家
猜你喜欢
随机推荐
6W+字记录实验全过程 | 探索Alluxio经济化数据存储策略
51单片机外设篇:点阵式LCD
Introduction and use of apifox (1).
Review: image saturation calculation formula and image signal-to-noise (PSNR) ratio calculation formula
51单片机外设篇:ADC
navicat新建数据库
区块元素、内联元素(<div>元素、span元素)
LeetCode刷题系列 -- 787. K 站中转内最便宜的航班
MySql copies data from one table to another table
提高软件测试能力的方法有哪些?看完这篇文章让你提升一个档次
MySQL导入sql文件的三种方法
How much does a test environment cost? Start with cost and efficiency
Alluxio为Presto赋能跨云的自助服务能力
goroutine (coroutine) in go language
navicat connects to MySQL and reports an error: 1045 - Access denied for user 'root'@'localhost' (using password YES)
Redis集群模式
一线大厂软件测试流程(思维导图)详解
go项目的打包部署
整合ssm(一)
go语言中的goroutine(协程)