Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obscure C syntax for Tomohiko Sakamoto's algorithm

I stumbled upon this version of the Sakamoto algorithm

dow(m,d,y){y-=m<3;return(y+y/4-y/100+y/400+"-bed=pen+mad."[m]+d)%7;}

I tried it on ideone.com and it actually works. I'm not interested in how the algorithm works, it's the syntax that baffles me.

I consider myself an intermediate C programmer and I have absolutely no idea what's going on in the "-bed=pen+mad."[m] part of the code.

What is that???

like image 606
mfloris Avatar asked Oct 16 '25 16:10

mfloris


1 Answers

That's array subscription on a string literal. Remember that a string literal is actually just a pointer to static memory.

The operation is equivalent to:

int m = 0;
char *str = "-bed=pen+mad.";
str[m];

char is a scalar type, and thus you can do arithmetic with the value.

like image 155
Oka Avatar answered Oct 18 '25 06:10

Oka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!