简单代码为:
#include<stdio.h>
int main()
{
printf("%s", "Hello Worldn");
return 0;
}
是否可以更改输出以显示变量类型、内存中占用的X字节以及它所能容纳的最大值?
thx提前
C在C11之前没有任何类型的反射。要打印变量的类型,您可以将其硬编码为格式字符串:
#include <stdio.h>
int main(void) {
int x = 0;
printf("x is an int with a value of %dn", x);
}
// prints "x is an int with a value of 0"
也可以使用链接答案中的宏。
要获取给定变量占用的内存量,可以使用sizeof
:
#include <stdio.h>
int main(void) {
int x = 0;
printf("x occupies %zu bytes in memoryn", sizeof(x));
}
// usually prints "x occupies 4 bytes in memory"
// (int's size is determined by the compiler)
存在一个limits.h
标头,它为所有内置类型的最大值和最小值定义了几个宏。然而,除了递增变量直到溢出之外,没有办法动态地获得给定类型的最大值。
#include <stdio.h>
#include <limits.h>
int main(void) {
printf("int has a maximum value of %dn", INT_MAX);
}
// usually prints "int has a maximum value of 2147483647"
// (int's maximum and minimum values are determined by the compiler)