How does this assignment of values ​​work?

I read K & R and the following code confuses me. Can someone explain this to me please. Thanks in advance.

int leap; leap = year%4 == 0 && year%100 !=0 || year%400 == 0; 
+4
source share
5 answers

leap assigned the result of conditional expressions.

The room around it can be a little simplified:

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

You will get 0 if it was not evaluated as true and 1 otherwise.

eg. for year = 2012 you get the following:

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

( year % 100 != 0) - this is not true, so again it equals 1

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

Then substituting these expressions in their value, we get:

leap = 1 && 1 || 0; - which returns us 1;

+12
source

The goal is to assign from 1 to leap if year is a leap year, and from 0 to leap if year not a leap year.

year is a leap year if it is divisible by 4 and not divisible by 100, or if year is divisible by 400. Otherwise, it is not. The right side of the job is the C code conversion for this leap year rule.

year%4 == 0 true if year is divisible by 4.
&& is and.
year%100 !=0 true if year not divisible by 100.
|| have or.
year%400 == 0 true if year is divisible by 400.

+3
source

It will return true (1) or false (0). You can even make your jump logical.

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

Suppose your year is 2000.

 leap = 2000%4 == 0 && 2000%100 !=0 || 2000%400 == 0 leap = true(1) && false(0) || true(1) leap =false(0) || true(1) leap = 1; 

Always use paranthesis to avoid confusion. In this case, you will not find any confusion, because the priority is from left to right.

This is how the instruction will be executed.

 %, ==, !=, &&, || 
+3
source

Basically, the result of the conditions is assigned to the jump .

Operation is easy

one.

 year%4 == 0
year%4 == 0 

2.

 year%100 !=0
year%100 !=0 

3.

 Result from 1 && Result from 2
Result from 1 && Result from 2 

4.

 year%400 == 0
year%400 == 0 

5.

 Result from 3 || Result from 4
Result from 3 || Result from 4 

6.

 leap = Result from 5
leap = Result from 5 


Hope the explanation is clear and that helps.

+1
source

Well, you already have good answers.

In short,

% gives the remainder

&& - logical operation AND

variable leap evaluates to 1 if the condition is true else 0

Here is another way to calculate a leap year:

 leap = ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)); 
+1
source

Source: https://habr.com/ru/post/1493567/


All Articles