从命令行使用 sizeof 编译 C 代码时出错

Errors compiling C code with sizeof from command line

我从 Linux 命令行在 Nano 中编写了以下代码,编译时出现错误:

我想知道我的代码需要更改什么才能正确编译。我正在尝试获取列出的每种数据类型中的位数以在一行上打印。

#include<stdio.h>

int main(void){
    char A;
    unsigned char B;
    int a;
    unsigned int b;
    long c;
    unsigned long d;
    float e;
    double f;
    long double g;

    printf(
        "%c %c %i %u %li %lu %f %lf %Lf\n",
         sizeof(char), sizeof(unsigned char),
         sizeof(int), sizeof(unsigned int),
         sizeof(long), sizeof(unsigned long),
         sizeof(float), sizeof(double), sizeof(long double)
    );

    return 0;
}

这是因为 unsigned char 被提升为一个 int(在正常的 C 实现中),因此一个 int 被传递给 printf 作为说明符 %c。但是,%c 需要一个 unsigned int,因此类型不匹配,并且 C 标准没有定义行为。 您可以执行以下方法: 1)尝试使用C11(标准版)。 2) 尝试使用 %zu.

sizeof operator returns an integer of type size_t, so you should use the appropriate printf 格式说明符 ("%zu")(假设 C99):

printf(
    "%zu %zu %zu %zu %zu %zu %zu %zu %zu\n",
     sizeof(char), sizeof(unsigned char),
     sizeof(int), sizeof(unsigned int),
     sizeof(long), sizeof(unsigned long),
     sizeof(float), sizeof(double), sizeof(long double)
);

但是,这会打印每种类型的 字节 的数量。如果您想要每种类型中的 的数量,请包括 <limits.h> 并将每个结果乘以 CHAR_BIT 以获得:

#include <limits.h>

/* ... */

printf(
    "%zu %zu %zu %zu %zu %zu %zu %zu %zu\n",
     sizeof(char) * CHAR_BIT, sizeof(unsigned char) * CHAR_BIT,
     sizeof(int) * CHAR_BIT, sizeof(unsigned int) * CHAR_BIT,
     sizeof(long) * CHAR_BIT, sizeof(unsigned long) * CHAR_BIT,
     sizeof(float) * CHAR_BIT, sizeof(double) * CHAR_BIT, sizeof(long double) * CHAR_BIT
);

IMO,如果您标记要打印的内容并在其自己的行上打印每个值,它看起来会更清楚,如下所示:

printf("Number of bits in char = %zu\n", sizeof(char) * CHAR_BIT);
printf("Number of bits in unsigned char = %zu\n", sizeof(unsigned char) * CHAR_BIT);
printf("Number of bits in int = %zu\n", sizeof(int) * CHAR_BIT);
printf("Number of bits in unsigned int = %zu\n", sizeof(unsigned int) * CHAR_BIT);
printf("Number of bits in long = %zu\n", sizeof(long) * CHAR_BIT);
printf("Number of bits in unsigned long = %zu\n", sizeof(unsigned long) * CHAR_BIT);
printf("Number of bits in float = %zu\n", sizeof(float) * CHAR_BIT);
printf("Number of bits in double = %zu\n", sizeof(double) * CHAR_BIT);
printf("Number of bits in long double = %zu\n", sizeof(long double) * CHAR_BIT);

并且可以用宏来减少(虽然宏不是最好的,但它们对重复代码很有用):

#define PRINT_BITS_IN_TYPE(type) \
    printf("Number of bits in " #type " = %zu\n", sizeof(type) * CHAR_BIT)

PRINT_BITS_IN_TYPE(char);
PRINT_BITS_IN_TYPE(unsigned char);
PRINT_BITS_IN_TYPE(int);
PRINT_BITS_IN_TYPE(unsigned int);
PRINT_BITS_IN_TYPE(long);
PRINT_BITS_IN_TYPE(unsigned long);
PRINT_BITS_IN_TYPE(float);
PRINT_BITS_IN_TYPE(double);
PRINT_BITS_IN_TYPE(long double);