Switch in C

#include <stdio.h>
#include <time.h>

void whatAmI(void* i, char type) {
    switch (type) {
        case 'b':
            printf("I'm a bool\n");
            break;
        case 'i':
            printf("I'm an int\n");
            break;
        default:
            printf("Don't know type %c\n", type);
    }
}

int main() {
    // Here's a basic switch.
    int i = 2;
    printf("Write %d as ", i);
    switch (i) {
        case 1:
            printf("one\n");
            break;
        case 2:
            printf("two\n");
            break;
        case 3:
            printf("three\n");
            break;
    }

    // You can use multiple cases in C by omitting the break statement.
    // We use the default case in this example as well.
    time_t now = time(NULL);
    struct tm *tm_struct = localtime(&now);
    int day = tm_struct->tm_wday;

    switch (day) {
        case 0:
        case 6:
            printf("It's the weekend\n");
            break;
        default:
            printf("It's a weekday\n");
    }

    // C doesn't have a direct equivalent to Go's switch without an expression,
    // but we can use if-else statements to achieve similar logic.
    int hour = tm_struct->tm_hour;
    if (hour < 12) {
        printf("It's before noon\n");
    } else {
        printf("It's after noon\n");
    }

    // C doesn't have type switches, but we can simulate it using a separate type parameter
    whatAmI(NULL, 'b');
    whatAmI(NULL, 'i');
    whatAmI(NULL, 's');

    return 0;
}

This C code demonstrates the use of switch statements and attempts to replicate the functionality of the original example as closely as possible. Here are some key points:

  1. C switch statements are similar to those in many other languages, including Go.

  2. In C, you need to use break statements to prevent fall-through behavior, unless that’s what you want.

  3. C doesn’t have a direct equivalent to Go’s switch without an expression. We use if-else statements to achieve similar logic.

  4. C doesn’t have type switches. We simulated this by adding a type parameter to the whatAmI function.

  5. To work with time, we use the time.h library, which provides functionality similar to Go’s time package.

To compile and run this program, you would typically use:

$ gcc -o switch switch.c
$ ./switch
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type s

Note that the exact output may vary depending on the time when you run the program.