1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

sizeof演算子

Posted at
sizeof演算子
#include <stdio.h>

int main(void)
{
    int n;
    printf("sizeof 1             = %zu\n", (sizeof  1));
    printf("sizeof-1             = %zu\n", (sizeof -1));
    printf("sizeof(unsigned)-1   = %zu\n", (sizeof(unsigned)-1));
    printf("sizeof(double)-1     = %zu\n", (sizeof(double)-1);
    printf("sizeof((double)-1)   = %zu\n", (sizeof((double)-1)));
}

実行結果

sizeof 1             = 4
sizeof-1             = 4
sizeof(unsigned)-1   = 3
sizeof(double)-1     = 7
sizeof((double)-1)   = 8

sizeof演算子は、引数で与えられた式・型のメモリサイズを返す。単位はbyte。

  • sizeof1, sizeof-1:
    1はint型なので4。-1も同じ
  • sizeof(unsigned)-1 :
    まずsizeof(unsigned)が評価され、unsigned int型なので4。そこから-1するので3
  • sizeof(double)-1:
    上に同じ。double型なので8。そこから-1するので7
  • sizeof((double)-1):
    こちらはまず()内の(double)-1が評価される。()の中では-1をdoubleに型キャストしている。引き算っぽい見た目してるけど、引き算ではない。
    また、sizeof(double-1)はエラーとなる。型名そのものを式にぶち込む(=オペランドとして使う)ことはできないから。
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?