user297850
user297850

Reputation: 8025

having difficulties in reading two lines of code

How to analyze these two following lines of code?

w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);

and

 w += 30 + (i % 2 ^ i >= 8);

Upvotes: 2

Views: 218

Answers (4)

Chubsdad
Chubsdad

Reputation: 25547

Here is how to analyze it

int main(){
    int w = 0;
    int y = 400;

    w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0); 

    int t1 = y % 100;
    int t2 = y % 400;
    
    int t3 = t1 | t2;

    bool t4 = (y % 4);

    int w1 = t3 & t4;
}

Note that t1 and t2, can be evaluated in any order t3 will be evaluated after t1 and t2 t4 can be evaluated before either t1 or t2

This requires familiarity with

operator associativity

operator precedence

sequence points

Leaving the other one also to be analyzed on similar lines

Upvotes: 0

Christian Ammer
Christian Ammer

Reputation: 7542

The first one seems to have to do something with the gregorian calandar.

Upvotes: 1

Starkey
Starkey

Reputation: 9781

The first one looks for leap years and adds 1 to w if it is. (every four year except ones divisible by 100 except ones divisible by 400.)

The second one looks for months that are 31 days. (Every every month except for months greater than 8, which repeats one month.)

Whoever wrote this code is just trying to be confusing and fancy. You should rewrite it to be more readable.

Upvotes: 11

AndersK
AndersK

Reputation: 36092

some kind of calculation of days of a year considering leap year?

Upvotes: 0

Related Questions