HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Printing the days of the week for every day this year

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thistheyeareveryweekprintingfordaydays

Problem

@chux pointed out that my attempted solution contained several problems. Since I screwed that up so badly, I figure that I should put my revised solution up for review.

#include 
#include 

/**
 * The current year (number of years since 1900)
 */
static int this_year(void) {
    time_t now = time(NULL);
    struct tm thetime;
    localtime_r(&now, &thetime);
    return thetime.tm_year;
}

static struct tm jan1(int yy) {
    struct tm t = { 0 };
    t.tm_year = yy;
    t.tm_mday = 1;
    t.tm_isdst = -1;
    return t;
}

int main(void) {
    int yy = this_year();

    for (struct tm t = jan1(yy); mktime(&t), t.tm_year == yy; t.tm_mday++) {
        char buf[80];
        if (!strftime(buf, sizeof buf, "%m/%d/%Y is a %A", &t)) {
            return 1;   // Unexpected failure
        }
        puts(buf);
    }
}


Concerns include standards compliance, portability, and correctness in all possible time zones. If possible, a more succinct way to obtain the current year and January 1 of the current year would be appreciated.

Solution

The only thing I have to say is that the use of strftime and %A means that the output will depend on the current locale setting.

This may be a bug or a feature depending on what your original intention was.

Also, the use of char buf[80] seems rather small for today's processors. The only way that strftime is going to fail is if it can't fit all of the output in the buffer. Since memory is cheap, you might as well make it char buf[256] or buf[1024]. This kinda of ties in with with the question of whether you expect to use this with custom locales.

Alternatives:

  • use strftime_l to use a specific locale



  • create your own array of weekday names instead of %A and use the tm_wday field to index into that array

Context

StackExchange Code Review Q#104297, answer score: 2

Revisions (0)

No revisions yet.