三元声明中的C逗号 [英] C comma in ternary statement
问题描述
int m = 5, d = 12, y = 1975, val;
// May 12, 1975
有人可以在下面的代码行中解释逗号运算符的功能/目的:
Can someone please explain the function/purpose of the comma operator in the line of code below:
val = (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7;
以上行由Mike Keith编写,用于计算给定日期的星期几(d =天,m =月,y =年).其中周日= 0,周一= 1,周二= 2,周三= 3,周四= 4,周五= 5,周六= 6. 我了解如果d + = m <3为真,则执行y--,否则执行y-2.我不了解y-2之后的逗号的目的.
The above line was written by Mike Keith to calculate the day of the week given the date (d = day, m = month, y = year). Where Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6. I understand that the y-- gets executed if d+=m<3 is true, else the y-2 is executed. What I don't understand is the purpose of the comma after y-2.
推荐答案
逗号运算符将要依次执行的表达式分开,就像;
一样.但是,使用,
时,它们构成了一个完整的表达式,其计算结果为最后一个子表达式的值.例如
The comma operator separates expressions to be executed one after the other, just like ;
. But with ,
they constitute one whole expression that evaluates to the value of the last sub-expression. For example
int i = 1;
int j = (++i, i*2);
printf("%i", j)
打印出4.
例如可以在for
表达式中使用,其中标头中需要3个表达式.例如
It can for example be used in for
expressions, where 3 expressions need to be in the header. For example
for(i = 0, j = 0; i < n; i++, j++)
这篇关于三元声明中的C逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!