-
-
Save rdammkoehler/a60693f6d8128182f4afce208a1089e2 to your computer and use it in GitHub Desktop.
More better C version of happyCDay in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
struct tm c_day = { | |
.tm_sec=0, | |
.tm_min=0, | |
.tm_hour= 0, | |
.tm_mday= 10, | |
.tm_mon= 9, | |
.tm_year=118, | |
.tm_wday=0, | |
.tm_yday= 0, | |
.tm_isdst= 0 | |
}; | |
int isCDay(time_t current_time) { | |
struct tm current_tm = *localtime(¤t_time); | |
current_tm.tm_sec = current_tm.tm_min = current_tm.tm_hour = current_tm.tm_wday = current_tm.tm_yday = 0; | |
return difftime(mktime(¤t_tm), mktime(&c_day)) == 0.0; | |
} | |
int main() { | |
static const char months[][12] = { | |
"January", "February", "March", | |
"April", "May", "June", | |
"July", "August", "September", | |
"October", "November", "December" | |
}; | |
time_t now = time(NULL); | |
if (isCDay(now)) { | |
printf("Happy C Day!.\n"); | |
} else { | |
struct tm current_time = *localtime(&now); | |
printf("The current month is %s.\n", months[current_time.tm_mon]); | |
} | |
} |
And his proposed C version:
#include <stdio.h>
#include <time.h>
#include <string.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
const char * months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
if (tm.tm_year == 2018 &&
strncmp(months[tm.tm_mon], "November", strlen(months[tm.tm_mon])) == 0 // why not strcmp() ?
&& tm.tm_mday == 10)
{
printf("Happy C Day!.\n");
} else {
printf("The current month is %s.\n", months[tm.tm_mon]);
}
}
and a link to the article that started it all:
https://blog.codacy.com/an-in-depth-explanation-of-code-complexity/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Putting his Go example for easier comparison: