C 語言實例 - 計算 int, float, double 和 char 位元組大小
使用 sizeof 操作符計算int, float, double 和 char四種變數位元組大小。
sizeof 是 C 語言的一種單目操作符,如C語言的其他操作符++、--等,它並不是函數。
sizeof 操作符以位元組形式給出了其運算元的存儲大小。
實例
#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;
}
運行結果:
Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of char: 1 byte
計算 long long, long double 位元組大小
實例
#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;
}
運行結果:
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