Skip to content

Instantly share code, notes, and snippets.

@rdammkoehler
Last active Jan 14, 2021
Embed
What would you like to do?
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]);
}
}
@rdammkoehler
Copy link
Author

rdammkoehler commented Jan 14, 2021

Just realized this will only work for a specific second on C-Day; working on a fix

@rdammkoehler
Copy link
Author

rdammkoehler commented Jan 14, 2021

ok, fixed, and broke out the evaluation for improved readability

@rdammkoehler
Copy link
Author

rdammkoehler commented Jan 14, 2021

So the c-day struct on line 4 is not particularly readable...working on a way to clean that up a bit

@rdammkoehler
Copy link
Author

rdammkoehler commented Jan 14, 2021

ok, labeled the c_day struct fields for readability. Hopefully that helps; the tm_year=118 is still irritating

@JeffHoover
Copy link

JeffHoover commented Jan 14, 2021

Putting his Go example for easier comparison:

func main() {
    year, month, day := time.Now().Date()
    output := fmt.Sprintf("The current month is %s", month)

    if month == time.November {
        if day == 13 {
            if year == 2018 {
                output = fmt.Sprintf("Happy Go day!")
            }
        }
    }

    fmt.Println(output)
}

@JeffHoover
Copy link

JeffHoover commented Jan 14, 2021

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

JeffHoover commented Jan 14, 2021

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