C 范例 - 计算 int, float, double 等字节大小

使用 sizeof 操作符计算int, float, double 和 char 四种变量字节大小。

sizeof 是 C 语言的一种单目操作符,如C语言的其他操作符++、--等,它并不是函数。

sizeof 操作符以字节形式给出了其操作数的存储大小。

/**
 * file: main.c
 * author: 简单教程(www.twle.cn)
 */

#include <stdio.h>

int main()
{
    int integerType;
    float floatType;
    double doubleType;
    char charType;

    // sizeof 操作符用于计算变量的字节大小
    printf("Size of int:    %ld bytes\n",sizeof(integerType));
    printf("Size of float:  %ld bytes\n",sizeof(floatType));
    printf("Size of double: %ld bytes\n",sizeof(doubleType));
    printf("Size of char:   %ld byte\n",sizeof(charType));

    return 0;
}

编译运行范例,输出结果如下

$ gcc main.c && ./a.out
Size of int:    4 bytes
Size of float:  4 bytes
Size of double: 8 bytes
Size of char:   1 byte


计算 long long, long double 字节大小

/**
 * file: main.c
 * author: 简单教程(www.twle.cn)
 */

#include <stdio.h>
int main()
{
    int a;
    long b;
    long long c;

    double e;
    long double f;


    printf("Size of int         = %ld bytes \n", sizeof(a));
    printf("Size of long        = %ld bytes\n", sizeof(b));
    printf("Size of long long   = %ld bytes\n", sizeof(c));

    printf("Size of double      = %ld bytes\n", sizeof(e));
    printf("Size of long double = %ld bytes\n", sizeof(f));

    return 0;
}

编译运行范例,输出结果如下

$ gcc main.c && ./a.out
Size of int         = 4 bytes
Size of long        = 8 bytes
Size of long long   = 8 bytes
Size of double      = 8 bytes
Size of long double = 16 bytes

C 语言范例

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.