前回に続いて、MIT Open CoursewareのPerformance Engineering of Software Systemsをやっていきます。
#データ型とそのサイズ
Cはたくさんのプリミティブ型をサポートしています。それは以下に示すとおり。
short s; //shortの符合付き整数
unsigned int i; //基本的な長さの符合なし整数
long l; //longの長さの整数
long long l; //特に長い符合付き整数
char c; //1個のASCII文字(1byte)
float f; //基本精度浮動小数点
double d; //倍精度浮動小数点
付記:ほとんどの64ビットマシンやコンパイラにおいて、基本的な精度の値(int,float)は32ビットです。shortはしばしば16ビットであり、longやdoubleはしばしば64ビットです。しかしながら、それらの型の精度はCの標準においては弱く定義されていて、マシンやコンパイラによって変わります。紛らわしいことに、時々intやlongは同じ精度です。そして、longとlong longも同じ精度であり、それらは共にiniより長いです。時々、intとlong、long longは同じ意味を持ちます。
使い捨ての変数や、精度内におさまる場合は、常にintを使用してください。この精度は違ったwordサイズにおいても機械の最大のパフォーマンスを発揮するように作られています。もしあなたがビットレベルの操作をしているなら、符合なしデータ型であるuint64_t
(unsigned 64 bit int)を使うのがいいでしょう。そうでないなら、明示的ではなく、intを使うのがいいでしょう。
さらに言うと、あなたが、使っているマシンのアーキテクチャを知っているなら、明示的なデータ型を代わりに使ってコードを書くのがいいでしょう。(以下のように)
#include <stdint.h>
uint64_t unsigned_64_bit_int;
int16_t signed_16_bit_int;
もっと複雑なデータ型をプリミティブ型からstructに構成することによって定義できます。例えば、以下のように定義できます。
typedef struct{
int id;
int year;
}student;
student you;
// 以下のコードでプロパティにアクセスできます。
you.id = 12345;
you.year = 3;
では、以下のコードで、データ型ごとのサイズを測ってみます。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main() {
printf("size of int is %lu\n", sizeof(int));
printf("size of short is %lu\n", sizeof(short));
printf("size of long is %lu\n", sizeof(long));
printf("size of char is %lu\n", sizeof(char));
printf("size of float is %lu\n", sizeof(float));
printf("size of double is %lu\n", sizeof(double));
printf("size of unsigned int is %lu\n", sizeof(unsigned int));
printf("size of long long is %lu\n", sizeof(long long));
printf("size of uint8_t is %lu\n", sizeof(uint8_t));
printf("size of uint32_t is %lu\n", sizeof(uint32_t));
printf("size of uint64_t is %lu\n", sizeof(uint64_t));
printf("size of uint_fast8_t is %lu\n", sizeof(uint_fast8_t));
printf("size of uint_fast16_t is %lu\n", sizeof(uint_fast16_t));
printf("size of uintmax_t is %lu\n", sizeof(uintmax_t));
printf("size of intmax_t is %lu\n", sizeof(intmax_t));
printf("size of __int128 is %lu\n", sizeof(__int128));
return 0;
}
実行結果は以下の通り
size of int is 4
size of short is 2
size of long is 8
size of char is 1
size of float is 4
size of double is 8
size of unsigned int is 4
size of long long is 8
size of uint8_t is 1
size of uint32_t is 4
size of uint64_t is 8
size of uint_fast8_t is 1
size of uint_fast16_t is 2
size of uintmax_t is 8
size of intmax_t is 8
size of __int128 is 16