Title here
Summary here
Based on the input provided, the selected target language is “cilk”. Here is the appropriate translation for the specified code example:
Switch statements express conditionals across many branches.
Here’s a basic switch
.
#include <cilk/cilk.h>
#include <stdio.h>
#include <time.h>
int main() {
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;
default:
printf("unknown\n");
}
// You can use commas to separate multiple expressions in the same `case` statement. We use the optional `default` case in this example as well.
time_t now = time(NULL);
struct tm *tm_struct = localtime(&now);
// Weekday starts from 0 (Sunday) to 6 (Saturday)
switch (tm_struct->tm_wday) {
case 0: // Sunday
case 6: // Saturday
printf("It's the weekend\n");
break;
default:
printf("It's a weekday\n");
}
// `switch` without an expression is an alternate way to express if/else logic. Here we also show how the `case` expressions can be non-constants.
switch (0) {
case 0 ... 11: // Using range for representing time before noon
if (tm_struct->tm_hour < 12) {
printf("It's before noon\n");
} else {
printf("It's after noon\n");
}
break;
}
// A type `switch` compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable will have the type corresponding to its clause.
void *item;
item = (void*)1; // Example item. In real scenarios, this might come from somewhere else.
switch (*(int*)&item) {
case 0:
printf("I'm a bool\n");
break;
case 1:
printf("I'm an int\n");
break;
default:
printf("Don't know type\n");
}
}
To run the program, compile the code and then execute the generated binary.
$ cilkcc -o switch switch.cilk
$ ./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
Now that we can run and build basic Cilk programs, let’s learn more about the language.
Next example: Arrays.