了解逗号运算符
Understand comma operator
int main()
{
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c= (b++, b++, b++);
printf("%d %d %d", a,b,c);
}
我是编程初学者。我不明白这个程序如何显示 6 9 8
的输出。
三个声明中都使用了,
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);
是comma operator。它计算第一个操作数 1 并丢弃它,然后计算第二个操作数和 return 它的值。因此,
int a = ((1,2), 3); // a is initialized with 3.
int b = ((++a, ++a), ++a); // b is initialized with 4+1+1 = 6.
// a is 6 by the end of the statement
int c = ((b++, b++), b++); // c is initialized with 6+1+1 = 8
// b is 9 by the end of the statement.
1 对于逗号运算符,计算顺序保证从左到右。
代码一点也不好,任何头脑正常的人都不会写它。那种代码大家不要花时间看,不过我还是会给出解释的。
逗号运算符,
表示“做左边的,丢弃任何结果,做右边的,然后return结果。将部分放在括号中对结果没有任何影响功能。
写得更清楚的代码是:
int a, b, c;
a = 3; // 1 and 2 have no meaning whatsoever
a++;
a++;
a++;
b = a;
b++;
b++;
c = b;
b++;
前增量运算符和 post 增量运算符在它们的行为方式上有所不同,这会导致 b 和 c 的值不同。
I am beginner in programming. I am not getting how does this program
shows me output of
明白就好comma operators and prefix ,postfix.
根据提供给您的链接中提到的规则
int a = (1,2,3); // a is initialized with 3 last argument .
int b = (++a, ++a, ++a); // a is incremented three time so becomes 6 and b initilized with 6 .
int c = (b++, b++, b++); // b incremented two times becomes 8 and c initialized with 8.
// b incremented once more time becomes 9
int main()
{
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c= (b++, b++, b++);
printf("%d %d %d", a,b,c);
}
我是编程初学者。我不明白这个程序如何显示 6 9 8
的输出。
三个声明中都使用了,
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);
是comma operator。它计算第一个操作数 1 并丢弃它,然后计算第二个操作数和 return 它的值。因此,
int a = ((1,2), 3); // a is initialized with 3.
int b = ((++a, ++a), ++a); // b is initialized with 4+1+1 = 6.
// a is 6 by the end of the statement
int c = ((b++, b++), b++); // c is initialized with 6+1+1 = 8
// b is 9 by the end of the statement.
1 对于逗号运算符,计算顺序保证从左到右。
代码一点也不好,任何头脑正常的人都不会写它。那种代码大家不要花时间看,不过我还是会给出解释的。
逗号运算符,
表示“做左边的,丢弃任何结果,做右边的,然后return结果。将部分放在括号中对结果没有任何影响功能。
写得更清楚的代码是:
int a, b, c;
a = 3; // 1 and 2 have no meaning whatsoever
a++;
a++;
a++;
b = a;
b++;
b++;
c = b;
b++;
前增量运算符和 post 增量运算符在它们的行为方式上有所不同,这会导致 b 和 c 的值不同。
I am beginner in programming. I am not getting how does this program shows me output of
明白就好comma operators and prefix ,postfix.
根据提供给您的链接中提到的规则
int a = (1,2,3); // a is initialized with 3 last argument .
int b = (++a, ++a, ++a); // a is incremented three time so becomes 6 and b initilized with 6 .
int c = (b++, b++, b++); // b incremented two times becomes 8 and c initialized with 8.
// b incremented once more time becomes 9