(This is a mild, geeky rant and probably won’t amuse you much if you’re not a software developer.)
So then. I and some other poor saps at work are tasked to migrate this large, 18-year old software product, written primarily in C, to a modern platform. For the most part it must remain as it is, in C. The people who wrote this old code are long gone, and I hope for their sakes — after my experience with their handiwork — that they’ve left the profession entirely.
I came across this specimen a few days ago. As you can see, it is a handy function for returning the current year as an integer. I’ve added line-number notes for reference.
int get_current_year(void)
{
time_t current_time;
char time_string[26], current_year[4];
int totlen, pos, i, int_year;
/*1*/ time(¤t_time);
/*2*/ current_time = time(NULL);
/*3*/ strcpy(time_string, ctime(¤t_time));
/*4*/ totlen = strlen(time_string);
/*5*/ pos = (totlen - 5);
/*6*/ for (i = 0; i < 4; i++)
{
current_year* = time_string[pos+i];
}
/*7*/ int_year = atoi(current_year);
/*8*/ return (int_year);
}
Works like a charm too. So far, anyway. In case your C is a little rusty, allow me to reveal the magician’s secrets:
[ol]
[li]Get the current time as an epoch value: the number of seconds passed since January 1, 1970.[/li][li]Get the current time as an ep — hey, didn’t we just do this?[/li][li]Convert the epoch time to a date-time string, and make a local copy of that string.[/li][li]Get the string’s length, even though C tells us it’s going to be exactly 26 characters, pretty much always. Still, you can’t be too sure of anything in this crazy, mixed-up world of ours, so better go find out. [/li][li]Get the position in the string where the four-digit year starts. Use needless parentheses for flair.[/li][li]Copy the year’s digits to make another string. Is this new string properly terminated, for what is to follow? Our author, ever the optimist, apparently had no doubts.[/li][li]Scan the four-digit string to get its integer value. Store the integer in case we need it later.[/li][li]Hey, where’s that integer? We need it! Return it to the caller, who’s probably wondering where we’ve been all day.[/li][/ol]
It would be hard to improve on this code — assuming its purpose is to completely crush the spirit of all who read it. If on the other hand its purpose is to return the current year as an integer, which would be the conventional interpretation I suppose, then I’d like to have a crack at the problem myself. You know, just a few tweaks maybe. Just a little polishing.
int get_current_year(void)
{
time_t current_time = time(NULL);
return localtime(¤t_time)->tm_year + 1900;
}
Hope you don’t mind, old programmer, wherever you are. I did keep the name at least.