LoginSignup
0
0

More than 3 years have passed since last update.

C言語で型のサイズを勘違いしてた話

Last updated at Posted at 2020-11-26

ことの起こり

昔(25年位前?)、C言語を習い始めたばかりくらいのときに

サイズ(bit)
int 16 or 32(実装による)
short 16
long 32

みたいな記述がよくあったと記憶しています。
なんとなくそのままの感覚でプログラム組んでたけど、今更ながら認識が間違ってることに気付いてしまったのでメモ。

そもそも

変数のサイズが重要な場合は int32_t とか UINT16 みたいな型を定義したりとかして使うんで、あまり深く考えてませんでした。

きっかけ

昔の誰かが作ったプログラム(今となっては経緯の分からないもの)の移植中に UINT32 が 64bit のサイズになってるのに気付いて確認したところ、、

typedef unsigned long UINT32;

みたいなところがありまして、これを環境に合わせて書き直せばいいんですけれども、感覚的に「これ正しくね?(32bit の表現として)」と思ってしまって、感覚と現実が合わなかったので一応確認したのです。

実際に確認してみた

確認用のプログラム

testSize.c
#include <stdio.h>

int main(){
    printf("size of:\n");
    printf(" int:                %zu\n", sizeof(int));
    printf(" short:              %zu\n", sizeof(short));
    printf(" long:               %zu\n", sizeof(long));
    printf(" long long:          %zu\n", sizeof(long long));
    printf(" unsigned int:       %zu\n", sizeof(unsigned int));
    printf(" unsigned short:     %zu\n", sizeof(unsigned short));
    printf(" unsigned long:      %zu\n", sizeof(unsigned long));
    printf(" unsigned long long: %zu\n", sizeof(unsigned long long));

    return 0;
}

うーん、わざわざここに載せるほどのものでもないですね。。

実行結果

Raspberry Pi 3 Model A+

$ ./testSize
size of:
 int:                4
 short:              2
 long:               4
 long long:          8
 unsigned int:       4
 unsigned short:     2
 unsigned long:      4
 unsigned long long: 8

これこれ。私の期待してた結果です。

Debian 10.6.0 < Virtual Box 6.1 < WIndows10

こっちが私の感覚と現実の違ってしまった環境。

$ ./testSize
size of:
 int:                4
 short:              2
 long:               8
 long long:          8
 unsigned int:       4
 unsigned short:     2
 unsigned long:      8
 unsigned long long: 8

あ、long がやっぱり 64bit なのね。
long long が 128bit になったりもしないのかぁ、、

結論

ただそれだけです。

long も実装によってサイズが違うのね。
short が 16bit 以外の実装環境もあるのかな?
ってか、そもそも規定がどうなってるのかきちんと調べろって話よね。。

昔の記憶だけでやってると思わぬところで勘違いしてしまってることありますね。。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0