如何将两个增量语句放在C ++'for'循环中? [英] How to put two increment statements in a C++ 'for' loop?

查看:307
本文介绍了如何将两个增量语句放在C ++'for'循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在中为 -loop条件增加两个变量,而不是一个。



例如:

  for(int i = 0; i!= 5; ++ i和++ j)
do_something(i,j);

这是什么语法?

解决方案

一个常见的习惯是使用逗号运算符来计算两个操作数,并返回第二个操作数。因此:

  for(int i = 0; i!= 5; ++ i,++ j)
do_something(i,j);



但是它真的是逗号运算符吗?



现在写过了,一个注释者建议它在for语句中实际上是一些特殊的语法糖,而不是一个逗号运算符。我在GCC检查如下:

  int i = 0; 
int a = 5;
int x = 0;

for(i; i <5; x = i ++,a ++){
printf(i =%da =%dx =%d \\\
,i,a,x );
}



我希望x能够获取a的原始值,已显示5,6,7 .. x。我得到的是这个

  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

但是,如果我把表达式括起来强迫解析器真正看到一个逗号运算符,我得到

  int main(){
int i = 0;
int a = 5;
int x = 0;

for(i = 0; i <5; x =(i ++,a ++)){
printf(i =%da =%dx =%d \\\
,i ,斧头);
}
}

i = 0 a = 5 x = 0
i = 1 a = 6 x = 5
i = 2 a = 7 x = 6 b

最初,我认为这表明它不是一个逗号运算符,但事实证明,这只是一个优先问题 - 逗号运算符有最可能的优先级,因此表达式x = i ++,a ++被有效地解析为(x = i ++),a ++



感谢所有的意见,这是一个有趣的学习经验,我已经使用C多年!


I would like to increment two variables in a for-loop condition instead of one.

So something like:

for(int i = 0; i != 5; ++i and ++j) 
    do_something(i,j);

What is the syntax for this?

解决方案

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);

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\n",i,a,x);
}

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\n",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

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++

Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!

这篇关于如何将两个增量语句放在C ++'for'循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆