tags:

views:

169

answers:

4

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);

Thanks.

A: 

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

Anders K.
+11  A: 

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.

Starkey
+1 agree fully.
Anders K.
It looks like the second one is actually trying to get the number of days in a month (w will be increased by 30 on all other months including Feb).
Mark B
There seems to be a pattern that a lot of C/C++ programs are written in a very complicated way like this. Is this usual in the industry?
I do'nt think it's normal to see complicated code in industry, but sometimes you do. I think as software developers mature, they stive for easier to read code that gets the job done. KISS. This isn't always the case though...
Starkey
+1  A: 

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

Christian Ammer
A: 

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

Chubsdad