Skip to content

Instantly share code, notes, and snippets.

@rdammkoehler
Last active January 14, 2021 18:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rdammkoehler/a60693f6d8128182f4afce208a1089e2 to your computer and use it in GitHub Desktop.
More better C version of happyCDay in C
#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(&current_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(&current_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]);
}
}
@JeffHoover
Copy link

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

@JeffHoover
Copy link

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