C Unsigned int 提供负值? [英] C Unsigned int providing a negative value?
问题描述
我有一个无符号整数,但是当我使用 %d 打印出来时,有时会出现负值?
I have an unsigned integer but when i print it out using %d there is sometimes a negative value there?
推荐答案
打印 %d
会将整数读取为带符号的十进制数,而不管其定义的类型.
Printing %d
will read the integer as a signed decimal number, regardless of its defined type.
要打印无符号数,请使用 %u
.
To print unsigned numbers, use %u
.
这是因为 C 处理变量参数的方式.编译器只是从堆栈中提取值(类型为 void*
并指向调用堆栈)并且 printf
必须从您提供的格式字符串中找出数据包含的内容它到.
This happens because of C's way to handle variable arguments. The compiler just pulls values from the stack (typed as void*
and pointing to the call stack) and printf
has to figure out what the data contains from the format string you give it to.
这就是您需要提供格式字符串的原因 - C 没有 RTTI 或基类"(例如,Java 中的 Object
)来获取通用或预定义的 toString
.
This is why you need to supply the format string - C has no way of RTTI or a 'base class' (Object
in Java, for example) to get a generic or predefined toString
from.
这篇关于C Unsigned int 提供负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!