How do I put two increment statements in a C++ #39;for#39; loop?(如何在 C++ for 循环中放置两个增量语句?)
问题描述
我想在 for
循环条件中增加两个变量而不是一个.
I would like to increment two variables in a for
-loop condition instead of one.
比如:
for (int i = 0; i != 5; ++i and ++j)
do_something(i, j);
这是什么语法?
推荐答案
一个常见的习惯用法是使用 逗号运算符 计算两个操作数,并返回第二个操作数.因此:
A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus:
for(int i = 0; i != 5; ++i,++j)
do_something(i,j);
但它真的是逗号运算符吗?
写完之后,一位评论者认为它实际上是 for 语句中的一些特殊语法糖,根本不是逗号运算符.我在 GCC 中进行了如下检查:
But is it really a comma operator?
Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows:
int i=0;
int a=5;
int x=0;
for(i; i<5; x=i++,a++){
printf("i=%d a=%d x=%d
",i,a,x);
}
我期望 x 获取 a 的原始值,因此它应该为 x 显示 5,6,7...我得到的是这个
I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this
i=0 a=5 x=0
i=1 a=6 x=0
i=2 a=7 x=1
i=3 a=8 x=2
i=4 a=9 x=3
但是,如果我将表达式括起来以强制解析器真正看到逗号运算符,我会得到这个
However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this
int main(){
int i=0;
int a=5;
int x=0;
for(i=0; i<5; x=(i++,a++)){
printf("i=%d a=%d x=%d
",i,a,x);
}
}
i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
最初我认为这表明它根本不像逗号运算符,但事实证明,这只是一个优先级问题 - 逗号运算符具有 最低可能的优先级,所以表达式 x=i++,a++ 被有效地解析为 (x=i++),a++
Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the lowest possible precedence, so the expression x=i++,a++ is effectively parsed as (x=i++),a++
感谢所有的评论,这是一次有趣的学习经历,我已经使用 C 多年了!
Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!
这篇关于如何在 C++ 'for' 循环中放置两个增量语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 'for' 循环中放置两个增量语句
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17