名前付きフィールド ( bar1
.. barN
) の快適さと、操作を自動化するためにループできる配列のようなものが必要です。まず、構造体 (メモリ内のフィールドの密な表現) を定義します。
struct VectorFields {
int a;
int b;
int c;
};
次に、その構造体で使用されるフィールドの数を知る必要があります。
#define VECTOR_FIELDS_LEN (sizeof(struct VectorFields) / sizeof(int))
(C++ では、いくつかのテンプレート マジック foo を使用できます。ここでは、単純なバリアントとしてプリプロセッサを使用します)。次に、 をstruct VectorFields
の配列と組み合わせてint
、サイズが一致するようにしunion
ます。
union Vector {
struct VectorFields fields;
int raw[VECTOR_FIELD_LEN];
};
(注:VECTOR_FIELD_LEN
コンパイラにとって既知の定数値である必要があるため、プリプロセッサは以前のものでした。) これで、名前 ( .fields.a
) またはインデックス ( .raw[0]
) のいずれかでデータにアクセスできるようになりました。それでは、 を足し合わせる関数を書きましょうVector
:
void vector_add(union Vector* result, union Vector* a, union Vector* b) {
int i;
for (i = 0; i < TUPLE_LEN; i++) {
result->raw[i] = a->raw[i] + b->raw[i];
}
}
次のように使用できます。
#include <stdio.h>
int main() {
union Vector a = { .fields = { 1, 2, 3 } };
union Vector b = { .fields = { 4, 5, 6 } };
union Vector sum;
vector_add(&sum, &a, &b);
printf("%d %d %d\n", sum.fields.a, sum.fields.b, sum.fields.c);
return 0;
}