为什么此代码打印 "False",尽管 int 的大小大于 -1?
Why this code is printing "False", though size of int is greater than -1?
根据下面的代码,int 的大小不大于-1。为什么会这样?为什么打印 "False" 而不是 "True"?
#include <stdio.h>
#include <stdlib.h>
int main() {
if(sizeof(int) > -1) {
printf("True\n");
}
else {
printf("False\n");
}
// Here size of int is equals to 4
printf("Size of int: %ld\n", sizeof(int));
return 0;
}
好吧 sizeof
returns size_t
是无符号的,当它与 int
比较时,int 被提升为无符号并且位表示全 1 现在被视为unsigned,比-1
大,也比sizeof int
大。这就是为什么这个结果。
size_t
的正确格式说明符是 %zu
。
根据下面的代码,int 的大小不大于-1。为什么会这样?为什么打印 "False" 而不是 "True"?
#include <stdio.h>
#include <stdlib.h>
int main() {
if(sizeof(int) > -1) {
printf("True\n");
}
else {
printf("False\n");
}
// Here size of int is equals to 4
printf("Size of int: %ld\n", sizeof(int));
return 0;
}
好吧 sizeof
returns size_t
是无符号的,当它与 int
比较时,int 被提升为无符号并且位表示全 1 现在被视为unsigned,比-1
大,也比sizeof int
大。这就是为什么这个结果。
size_t
的正确格式说明符是 %zu
。