Created
August 8, 2020 12:31
-
-
Save lufia/55397ea9700bf77850354e6888124b37 to your computer and use it in GitHub Desktop.
C言語の自動変数で構造体の初期化を検証するコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <u.h> | |
#include <libc.h> | |
typedef struct Time Time; | |
typedef union Metric Metric; | |
typedef struct Value Value; | |
struct Time { | |
vlong sec; | |
}; | |
union Metric { | |
double f; | |
long n; | |
}; | |
struct Value { | |
char *name; | |
Metric metric; | |
Time t; | |
}; | |
int | |
strequal(char *s, char *t) | |
{ | |
if(s == nil || t == nil) | |
return s == t; | |
return strcmp(s, t) == 0; | |
} | |
void | |
vdiff(Value *v, Value *want, char *name) | |
{ | |
fprint(2, "%s:\n", name); | |
if(!strequal(v->name, want->name)) | |
fprint(2, ".name = %s; want %s\n", v->name, want->name); | |
if(memcmp(&v->metric, &want->metric, sizeof(Metric)) != 0){ | |
fprint(2, ".metric.f = %f; want %f\n", v->metric.f, want->metric.f); | |
fprint(2, ".metric.n = %ld; want %ld\n", v->metric.n, want->metric.n); | |
} | |
if(memcmp(&v->t, &want->t, sizeof(Time)) != 0) | |
fprint(2, ".t.sec = %d; want %d\n", v->t.sec, want->t.sec); | |
} | |
void | |
main(void) | |
{ | |
Value v0, v1; | |
Value a[4] = { | |
/* [0]: 全部省略されたstructを0埋めする */ | |
[1] = { | |
.name = "cpu.usage", | |
/* .metric: unionは残りのフィールドを0埋めしない */ | |
.metric = { | |
.n = 21, | |
}, | |
/* .t: 名前を省略した場合は前のフィールドから続ける */ | |
{ | |
.sec = 100, | |
}, | |
}, | |
{ | |
/* .name: ポインタ値を省略した場合はnil */ | |
.metric = { | |
.f = 0.2, | |
}, | |
/* .t: 構造体を省略した場合は各要素を0埋めする */ | |
}, | |
/* [3]: 残っている要素を0埋めする */ | |
}; | |
memset(&v0, 0, sizeof v0); | |
vdiff(&a[0], &v0, "a[0]"); | |
memset(&v1, 0, sizeof v1); | |
v1.name = "cpu.usage"; | |
v1.metric.n = 21; | |
v1.t.sec = 100; | |
vdiff(&a[1], &v1, "a[1]"); | |
memset(&v1, 0, sizeof v1); | |
v1.metric.f = 0.2; | |
vdiff(&a[2], &v1, "a[2]"); | |
vdiff(&a[3], &v0, "a[3]"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment