Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

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.

like image 982
01001000 01101001 Avatar asked Dec 05 '22 22:12

01001000 01101001


2 Answers

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)

prints out 4.

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++)
like image 91
tmlen Avatar answered Dec 28 '22 02:12

tmlen


The statement

val = (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7;  

is equivalent to

val = ( (d+=(m<3?y--:(y-2))), (23*m/9+d+4+y/4-y/100+y/400) ) % 7; 

, is comma operator (evaluates its first operand and discards the result, and then evaluates the second operand and returns this value) here.

Left operand of comma operator, ie., (d+=m<3?y--:y-2) is evaluated and side effect to y take place. Value of this expression is discarded. Right operand (23*m/9+d+4+y/4-y/100+y/400) will be evaluated and its value is the value of expression (d+=m<3?y--:y-2), (23*m/9+d+4+y/4-y/100+y/400).

like image 29
haccks Avatar answered Dec 28 '22 00:12

haccks