Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this value assignment work? [closed]

Tags:

c

I'm reading K&R and the following code confuses me. Can someone explain it to me please. Thanks in advance.

int leap;
leap = year%4 == 0 && year%100 !=0 || year%400 == 0;
like image 373
AuA Avatar asked Dec 01 '22 03:12

AuA


1 Answers

leap is assigned the result of the conditional expressions.

Putting parenthesis around it might make it a little easier to follow:

leap = ((year % 4 == 0) && (year % 100 !=0) || (year % 400 == 0));

You will get 0 if this didn't evaluate to true and 1 otherwise.

E.g. for year = 2012 you get the following:

(year % 4 == 0) - this is true so this is equal to 1

(year % 100 != 0) - this is not true so again equal to 1

(year % 400 == 0) - not true and equal to 0

Then substituting these expressions with their value we get:

leap = 1 && 1 || 0; - which gives us back 1;

like image 95
Nobilis Avatar answered Dec 05 '22 06:12

Nobilis